可重入锁、不可重入锁
- 可重入锁可以延续使用
- 不可重入锁不可以延续使用
不可重入锁简单实现
package com.tsymq.thread.advanced;
// 不可重入锁
class UnReentrantLock {
// 是否被锁定
private boolean isLocked = false;
// 锁定
public synchronized void lock() throws InterruptedException{
while(isLocked){
wait();
}
isLocked = true;
}
// 解锁
public synchronized void unLock() throws InterruptedException{
isLocked = false;
notify();
}
}
public class LockTest {
// 不可重入锁
UnReentrantLock unReentrantLock = new UnReentrantLock();
public void useUnReentrantLock() throws InterruptedException {
unReentrantLock.lock();
add1();
unReentrantLock.unLock();
}
public void add1() throws InterruptedException {
unReentrantLock.lock();
System.out.println("add1");
unReentrantLock.unLock();
}
public static void main(String[] args) throws InterruptedException {
LockTest lockTest = new LockTest();
lockTest.useUnReentrantLock(); // 线程一直等待,程序卡住
}
}
结果:程序一直卡住,无任何输出
可重入锁简单实现
package com.tsymq.thread.advanced;
// 可重入锁
class MyReentrantLock {
// 是否被锁定
private boolean isLocked = false;
// 被哪个线程锁定
private Thread lockedBy = null;
// 被锁计数
private int lockedCount = 0;
// 锁定
public synchronized void lock() throws InterruptedException{
Thread thread = Thread.currentThread();
while(isLocked && lockedBy != thread){
wait();
}
isLocked = true;
lockedCount++;
lockedBy = thread;
}
// 解锁
public synchronized void unLock() throws InterruptedException{
if (Thread.currentThread() == this.lockedBy){
lockedCount--;
if (lockedCount == 0){
isLocked = false;
notify();
}
}
}
}
public class LockTest {
// 不可重入锁
MyUnReentrantLock myUnReentrantLock = new MyUnReentrantLock();
// 可重入锁
MyReentrantLock myReentrantLock = new MyReentrantLock();
// 使用不可重入锁
public void useUnReentrantLock() throws InterruptedException {
myUnReentrantLock.lock();
add1();
myUnReentrantLock.unLock();
}
public void add1() throws InterruptedException {
myUnReentrantLock.lock();
System.out.println("add1");
myUnReentrantLock.unLock();
}
// 使用可重入锁
public void useReentrantLock() throws InterruptedException {
myReentrantLock.lock();
add2();
myReentrantLock.unLock();
}
public void add2() throws InterruptedException {
myReentrantLock.lock();
System.out.println("add2");
myReentrantLock.unLock();
}
public static void main(String[] args) throws InterruptedException {
LockTest lockTest = new LockTest();
lockTest.useReentrantLock(); // 输出 add2
}
}
结果:控制台输出 add2