之所以采用booleanLock是因为传统的synchronized无法控制时间,也不可中断。
public interface Lock{
void lock() throws InterruptedException;
void lock(long mills) throws InterruptedException ,TimeoutException;
void unlock();
List<Thread> getBlockedThreads();
}
public class BooleanLock implements Lock{
private Thread currentThread;
private boolean locked = false;//由于Lock调用时上下文在主线程中,所以locked没必要使用volatile修饰
private final List<Thread> blockedList = new ArrayList<Thread>();
public void lock()throws InterruptedException{
synchronized(this){
while(locked){
if(!blockedList.contains(Thread.currentThread)){
blockedList.add(Thread.currentThread);
}
this.wait();
}
blockedList.remove(Thread.currentThread);
this.locked = true;
this.currentThread = Thread.currentThread;
}
}
public void lock(long mils)throws InterruptedException ,TimeoutException{
synchronized(this){
if(mils <= 0){
this.lock();
}else{
long remainingMills = mils;
long endMills = currentTimeMills + remainingMills;
while(!locked){
if(remainingMills <= 0){
throw new TimeoutException();
}
if(!blockedList.contains(Thread.currentThread)){
blockedList.add(Thread.currentThread);
}
this.wait(remainingMills);
remainingMills = endMills -currentTimeMills;
}
}
blockedList.remove(Thread.currentThread);
this.locked = true;
this.currentThread = Thread.currentThread;
}
}
public void unlock(){
synchronized(this){
if(this.currentThread == Thread.currentThread){
this.locked = false;
this.notifyAll();
}
}
}
}