1.ReentrantLock的介绍
- ReentrantLock是独占锁且是可重入的
- ReentrantLock可以实现公平锁
- ReentrantLock可中断响应
- ReentrantLock可获取锁时限时等待
2.使用ReentrantLock的lock方法获取锁,unlock方法释放锁,模拟多线程实例如下:
public class LockDemo {
private static Lock lock = new ReentrantLock ();
private static CountDownLatch countDownLatch = new CountDownLatch (10);
private static int num = 0;
public static void inCreate() {
// 获取锁
lock.lock ();
num++;
// 释放锁
lock.unlock ();
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread (() -> {
for (int j = 0; j < 10000; j++) {
inCreate ();
}
// 线程执行结束执行countDown,对计数减一
countDownLatch.countDown ();
}).start ();
}
while (true) {
// 所有线程执行完毕,输出num
if (countDownLatch.getCount () == 0) {
System.out.println (num);
break;
}
}
}
}
控制台输出:
100000
3.总结
ReentrantLock是可重入的独占锁。比起synchronized功能更加丰富,支持公平锁实现,支持中断响应以及限时等待等等。可以配合一个或多个Condition条件方便的实现等待通知机制