ReentrantLock与锁

ReentrantLock与锁之间的区别及使用~

  • ReentrantLock(重入锁)与synchronize区别
    • 可重入性:两个都是可以重入的进行锁的计数
    • 锁的实现:ReentrantLock用的是程序实现(用户态),synchronized用的是JVM实现(内核态)
    • 性能的区别:synchronized(轻量级锁,偏向锁)经过优化后和ReentrantLock性能差不多
    • 功能区别:ReentrantLock更加的灵活(细粒度高),synchronized更加便利
  • ReentrantLock(重入锁)独有的功能
    • 可以指定是公平锁还是非公平锁
    • 提供了一个Condition类,可以分组唤醒需要唤醒的线程
    • 提供能够中断等待锁的线程的机制,lock.lockInterrupibly
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//ReentrantLock及Condition使用
@Slf4j
public class ConditionExample {
public static void main(String[] args) {
ReentrantLock reentrantLock = new ReentrantLock();
Condition condition = reentrantLock.newCondition();

new Thread(() -> {
try{
reentrantLock.lock();
log.info("wait signal");// 1
condition.await();
}catch(InterruptedException e){
e.printStackTrace();
}
log.info("get signal");// 4
reentrantLock.unlock();
}).start();

new Thread(() -> {
reentrantLock.lock();
log.info("get Lock");// 2
try{
Thread.sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}
condition.signalAll();
log.info("send signal ~");// 3
reentrantLock.unlock();
}).start();

}
}