ReentrantLock 是完全可以替代 synchronized,synchronized 能干的 ReentrantLock 都能干,但 ReentrantLock 能干的 synchronized 不一定能干,例如:
-
ReentrantLock 提供了 tryLock() 方法,会尝试获取锁,如果获取锁了就返回 true,没获取就返回 false,但无论有没有获取锁,都会继续执行之后的代码;此外 tryLock() 还有一个重载的方法 tryLock(long time, TimeUnit unit),可以指定尝试的时间,详情请参考如下文章:Lock 之 tryLock
-
ReentrantLock 还提供了 lockInterruptibly() 方法获取锁,使用这种方法获取锁失败阻塞后是可以响应中断的,详情请参考如下文章:中断异常测试
-
ReentrantLock 提供了公平锁,使用方式如下:
Lock lock = new ReentrantLock(true);
不传参时默认是非公平锁,传入 true 是公平锁,传入 false 是非公平锁。
ReentrantLock 和 synchronized 主要区别总结如下:
- ReentrantLock 使用 CAS 实现,synchronized 是锁升级。
- tryLock()
- lockInterruptibly()
- 公平锁