一个简单的锁
提供一个禁戒值,表示当前锁占用情况。
定义一个lock接口
package com.puqiuyu.thread.blog;
/**
* 简单实现下就行
* @author sunday
*
*/
public interface Lock {
void lock() throws InterruptedException;
void unlock() throws InterruptedException;
}
booleanlock实现类
package com.puqiuyu.thread.blog;
/**
* 自己实现一个锁
*
* 锁的作用:
* 检票的窗口一次只能有一个人通过。
*
*
* 这个锁就是守住入口、出口。 保证一次仅有一个人通过
*
*
* @author sunday
*
*/
public class BooleanLock implements Lock{
private boolean using = false;
private Thread currentThread;
@Override
public synchronized void lock() throws InterruptedException {
while(using) {
this.wait();
}
using = true;
currentThread = Thread.currentThread();
}
@Override
public synchronized void unlock() throws InterruptedException {
if (currentThread != Thread.currentThread()) {//非当前线程乱调
return;
}
this.notifyAll();
using = false;
}
}