选自:java线程2e。
类似于jdk1.5中的reentrantlock实现。
类似于jdk1.5中的reentrantlock实现。
package com.cxz.tools;
public class BusyFlag {
protected Thread busyFlag = null;
protected int busyCount = 0;
public synchronized void getBusyFlag() throws InterruptedException {
while (tryGetBusyFlag() == false) {
wait();
}
}
public synchronized void freeBusyFlag() {
if (busyFlag == Thread.currentThread()) {
busyCount--;
if (busyCount == 0) {
busyFlag = null;
notify();
}
}
}
private boolean tryGetBusyFlag() {
if (busyFlag == null) {
busyFlag = Thread.currentThread();
busyCount = 1;
return true;
}
if (busyFlag == Thread.currentThread()) {
busyCount++;
return true;
}
return false;
}
}