1. 什么是ReentrantLock?
ReentrantLock称为可重入锁,或者中心锁。
ReentrantLock加锁后需要手动解锁。
2.ReentrantLock的使用
方法 | 含义 | 备注 |
lock | 加锁 | 加锁以后不会自动解锁,需要手动解锁(unlock)。当一个线程lock以后,其他线程lock时,会加入等待队列。 |
unlock | 解锁 | 释放锁,和一般和lock成对使用 |
tryLock | 尝试申请锁 | 尝试加锁,申请失败不加入等待队列。如果锁被占用,则加锁失败,返回false。 |
验证
/**
* 测试ReentrantLock尝试加锁
*
* @author zhouronghua
* @time 2021/6/30 5:58 下午
*/
public class TestReentrantTryLock {
/**
* ReentrantLock
*/
private final ReentrantLock reentrantLock = new ReentrantLock();
/**
* 加锁处理
*
* @author zhouronghua
* @time 2021/6/30 6:00 下午
*/
private void lockProcessor() {
try {
System.out.println(Thread.currentThread().getName() + " 获得ReentrantLock锁");
reentrantLock.lock();
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
System.out.println(Thread.currentThread().getName() + " lockProcessor释放ReentrantLock锁");
}
}
/**
* 尝试申请锁处理
*
* @author zhouronghua
* @time 2021/6/30 6:00 下午
*/
private void tryLockProcessor() {
System.out.println(Thread.currentThread().getName() + " 尝试申请ReentrantLock锁");
boolean isLockSuccess = false;
while (true) {
try {
isLockSuccess = reentrantLock.tryLock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 申请ReentrantLock锁" + (isLockSuccess ? "成功" : "失败"));
if (isLockSuccess) {
break;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (isLockSuccess) {
reentrantLock.unlock();
System.out.println(Thread.currentThread().getName() + " tryLockProcessor释放ReentrantLock锁");
}
}
}
}
/**
* main入口
*
* @param args 参数
* @author zhouronghua
* @time 2021/6/30 5:59 下午
*/
public static void main(String[] args) {
TestReentrantTryLock tryLock = new TestReentrantTryLock();
new Thread(tryLock::lockProcessor, "thread 1").start();
new Thread(tryLock::tryLockProcessor, "thread 2").start();
}
}
只有lock释放以后,tryLock才成功。
thread 1 获得ReentrantLock锁
thread 2 尝试申请ReentrantLock锁
thread 2 申请ReentrantLock锁失败
thread 2 申请ReentrantLock锁失败
thread 2 申请ReentrantLock锁失败
thread 2 申请ReentrantLock锁失败
thread 2 申请ReentrantLock锁失败
thread 2 申请ReentrantLock锁失败
thread 2 申请ReentrantLock锁失败
thread 2 申请ReentrantLock锁失败
thread 2 申请ReentrantLock锁失败
thread 1 lockProcessor释放ReentrantLock锁
thread 2 申请ReentrantLock锁失败
thread 2 申请ReentrantLock锁成功
thread 2 tryLockProcessor释放ReentrantLock锁