实现的目标
实现自己的锁,使线程同步。提供了两个lock方法一个带有参数(timeout)当固定时间内没有执行的线程就不让他去执行了。
1.创建接口 Lock定义了超时异常,当等待强锁的时间超过timeout让他超时异常
public interface Lock {
class TimeoutException extends Exception{
TimeoutException(String message){
super(message);
}
}
void lock() throws InterruptedException;
void lock(long timeout) throws InterruptedException, TimeoutException;
void unlock();
}
2.创建接口的实现类MyLock
定义有个waitSet来存放阻塞线程。定义isHold来决定是不是当前的锁已经被持有了。当isHold为true表示当前的显示锁被拿走了,其他线程就得等着进入waitSet队列。当线程拿到锁了,就立刻将isHold给置为true
在释放锁的时候就需要将所有线程notify()让其他线程争抢显示锁。(其实就是通过isHold中间变量来控制是不是拿到锁了!为什么不用volatile?肯定要给方法加锁防止逻辑乱掉,加锁方法里面就不用volatile了啊)
public class MyLock implements Lock {
private boolean isHold = false;
private final List<Thread> WAIT_SET = new LinkedList<>();
private Thread currentThread;
@Override
public synchronized void lock() throws InterruptedException {
while(isHold){
this.wait();
WAIT_SET.add(Thread.currentThread());
}
currentThread = Thread.currentThread();
WAIT_SET.remove(Thread.currentThread());
isHold = true;
}
@Override
public synchronized void lock(long timeout) throws InterruptedException,TimeoutException {
Long hasRmaining = timeout;
Long endTime = System.currentTimeMillis() + timeout;
while(isHold){
if(hasRmaining <= 0)
{
throw new TimeoutException("超时异常");
}
WAIT_SET.add(Thread.currentThread());
this.wait(timeout);
hasRmaining = endTime - System.currentTimeMillis();
}
WAIT_SET.remove(Thread.currentThread());
currentThread = Thread.currentThread();
isHold = true;
}
public Collection getWitSet(){
return Collections.unmodifiableCollection(WAIT_SET);
}
@Override
public synchronized void unlock() {
if(currentThread == Thread.currentThread()){
isHold = false;
this.notifyAll();
}
}
}