解释

A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities. 可重入的互斥锁,基本功能和synchronized相同,但是具有扩展性

原理分析

先从ReentrantLock的源代码看起,仅列出核心的代码,又出现了常见的AbstractQueuedSynchronizer

  1. public class ReentrantLock implements Lock, java.io.Serializable{
  2. private final Sync sync;
  3. abstract static class Sync extends AbstractQueuedSynchronizer {
  4. }
  5. // 非公平锁
  6. static final class NonfairSync extends Sync{
  7. }
  8. // 公平锁
  9. static final class FairSync extends Sync{
  10. }
  11. // 默认是非公平锁
  12. public ReentrantLock() {
  13. sync = new NonfairSync();
  14. }
  15. //
  16. public Condition newCondition() {
  17. return sync.newCondition();
  18. }
  19. //获取锁
  20. public void lock() {
  21. sync.lock();
  22. }
  23. // 释放锁
  24. public void unlock() {
  25. sync.release(1);
  26. }
  27. }

使用方式

练习题目