可重入锁

java中用synchronized实现可重入锁的基本原理

package Thread;
//可重入锁(使得再得到一个锁时 不会等待 然后这个锁可以继续使用)
public class TestLock {
Relock lock = new Relock();
public void a() throws InterruptedException {
lock.lock();
System.out.println(lock.getHoldCount());
doSomething();
lock.unlock();
System.out.println(lock.getHoldCount());
}
//不可重入
public void doSomething() throws InterruptedException {
lock.lock();
System.out.println(lock.getHoldCount());
lock.unlock();
System.out.println(lock.getHoldCount());
}
public static void main(String[] args) throws InterruptedException {
TestLock test = new TestLock();
test.a();
Thread.sleep(1000);
System.out.println(test.lock.getHoldCount());
}
}
//可重入锁
class Relock{
//是否占用
private boolean isLocked = false;
private Thread lockedBy = null;//存储线程
private int holdCount = 0;
//使用锁
public synchronized void lock() throws InterruptedException {
Thread t = Thread.currentThread();
while(isLocked && lockedBy!= t) {
wait();
}
isLocked = true;
lockedBy = t;
holdCount ++;
}
//释放锁
public synchronized void unlock() {
if(Thread.currentThread() == lockedBy) {
holdCount–;
if(holdCount == 0) {
isLocked = false;
notify();
lockedBy = null;
}
}

}
public int getHoldCount() {
	return holdCount;
}

}

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页