十五、并发编程之写自己的公平锁

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29479041/article/details/84992733
package com.roocon.thread.ta3;

import java.util.ArrayList;
import java.util.List;

public class FairLock {
	private boolean isLocked = false;
	private Thread lockingThread = null;
	private List<QueueObject> waitingThreads = new ArrayList<QueueObject>();//等待线程队列

	//加锁
	public void lock() throws InterruptedException {
		QueueObject queueObject = new QueueObject();//新建QueueObject
		synchronized (this) {
			waitingThreads.add(queueObject);//把新建的QueueObject放在等待队列中
		}
		try {
			queueObject.doWait();//调用等待方法
		} catch (InterruptedException e) {
			synchronized (this) {
				waitingThreads.remove(queueObject);
			}
			throw e;
		}
	}

	//释放锁
	public synchronized void unlock() {
		if (this.lockingThread != Thread.currentThread()) {
			throw new IllegalMonitorStateException("Calling thread has not locked this lock");
		}
		isLocked = false;
		lockingThread = null;
		if (waitingThreads.size() > 0) {
			waitingThreads.get(0).doNotify();//叫醒等待队列里第一个QueueObject
		}
	}
}
package com.roocon.thread.ta3;

public class QueueObject {
	private boolean isNotified = false;//是否唤醒

	//等待
	public synchronized void doWait() throws InterruptedException {
		while (!isNotified) {//只要没被唤醒就一直等待
			this.wait();
		}
		//被唤醒了,就把isNotified设置成false
		this.isNotified = false;
	}
	//唤醒
	public synchronized void doNotify() {
		this.isNotified = true;//是否叫醒变成true
		this.notify();//唤醒
	}

	public boolean equals(Object o) {
		return this == o;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_29479041/article/details/84992733