相对于 synchronized 它具备如下特点

  1. 等待状态的线程可中断
  2. 可以设置超时时间
  3. 可以设置为公平锁,默认为非公平
  4. 支持多个条件变量,即对于不满足条件的线程可以放到不同的集合中等待

与 synchronized 一样,都支持可重入

基本语法

  1. reentrantLock.lock(); // 获取锁
  2. try {
  3. // 临界区
  4. } finally {
  5. reentrantLock.unlock(); // 释放锁
  6. }

可重入

可重入是指同一个线程如果首次获得了这把锁,那么因为它是这把锁的拥有者,因此有权利再次获取这把锁。如果是不可重入锁,那么第二次获得锁时,自己也会被锁挡住。

  1. static ReentrantLock lock = new ReentrantLock();
  2. public static void main(String[] args) {
  3. method1();
  4. }
  5. public static void method1() {
  6. lock.lock();
  7. try {
  8. log.debug("execute method1");
  9. method2();
  10. } finally {
  11. lock.unlock();
  12. }
  13. }
  14. public static void method2() {
  15. lock.lock();
  16. try {
  17. log.debug("execute method2");
  18. } finally {
  19. lock.unlock();
  20. }
  21. }

输出

  1. 17:59:11.862 [main] c.TestReentrant - execute method1
  2. 17:59:11.865 [main] c.TestReentrant - execute method2

可打断

  1. ReentrantLock lock = new ReentrantLock();
  2. public static void main(String[] args) {
  3. Thread t1 = new Thread(() -> {
  4. log.debug("启动...");
  5. try {
  6. lock.lockInterruptibly(); //可被打断的锁
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. log.debug("等锁的过程中被打断"); //没有获得锁就被打断跑出的异常
  10. return; //异常返回
  11. }
  12. try {
  13. log.debug("获得了锁");
  14. } finally {
  15. lock.unlock();
  16. }
  17. }, "t1");
  18. lock.lock(); //主线程先获得锁
  19. log.debug("获得了锁");
  20. t1.start();
  21. try {
  22. sleep(1);
  23. t1.interrupt(); //打断t1线程
  24. log.debug("执行打断");
  25. } finally {
  26. lock.unlock();
  27. }
  28. }
  • **lock.lockInterruptibly()**:和 Lock.lock() 方法的区别是 当没有获取到锁进入阻塞队列后,可以被 interrupt() 方法打断。

输出

18:02:40.520 [main] c.TestInterrupt - 获得了锁
18:02:40.524 [t1] c.TestInterrupt - 启动... 
18:02:41.530 [main] c.TestInterrupt - 执行打断
java.lang.InterruptedException at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireInterruptibly(AbstractQueuedSynchronizer.java:898) 
     at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1222) 
     at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:335) 
     at cn.itcast.n4.reentrant.TestInterrupt.lambda$main$0(TestInterrupt.java:17) 
     at java.lang.Thread.run(Thread.java:748) 
18:02:41.532 [t1] c.TestInterrupt - 等锁的过程中被打断

如果是不可中断模式,即使用Lock.lock()方法来获取锁,那么即使使用了 interrupt() 也不会让等待中断。

锁超时

  1. 立刻失败

    Thread t1 = new Thread(() -> {
    
     log.debug("尝试获得锁");
    
     try {
    
         if (! lock.tryLock()) {
    
             log.debug("获取立刻失败,返回");
    
             return;
         }
    
         log.debug("获得到锁");
    
     } finally {
         lock.unlock();
     }
    }, "t1")
    
  • **lock.tryLock()**:会返回是否获取到锁。也支持可打断。
  1. 超时失败
    Thread t1 = new Thread(() -> {
     log.debug("尝试获得锁");
     try {
         if (! lock.tryLock(1, TimeUnit.SECONDS)) {
             log.debug("获取等待1s后失败,返回");
             return;
         }
     } catch (InterruptedException e) {
         e.printStackTrace();
         log.debug("获取不到锁");
         return;
     }
     try {
         log.debug("获得到锁");
     } finally {
         lock.unlock();
     }
    }, "t1");
    
  • **lock.tryLock(1, TimeUnit.SECONDS)**:如果没有获取到锁,会继续尝试一秒,如果还是没有获取到锁,则返回 false。

公平锁

synchronized 锁中,在EntryList等待的锁在竞争时不是按照先到先得来获取锁的,所以说synchronized锁时不公平的;ReentranLock锁默认是不公平的,但是可以通过设置实现公平锁。本意是为了解决线程的饥饿问题,但是公平锁一般没有必要,会降低并发度,使用 trylock() 也可以实现。

条件变量

synchronized 中也有条件变量,就是我们讲原理时那个 waitSet 休息室,当条件不满足时进入 waitSet 等待。 ReentrantLock 的条件变量比 synchronized 强大之处在于,它是支持多个条件变量的,这就好比

  1. synchronized 是那些不满足条件的线程都在一间休息室等消息。
  2. 而 ReentrantLock 支持多间休息室,有专门等烟的休息室、专门等早餐的休息室、唤醒时也是按休息室来唤醒。

    @Slf4j(topic = "c.Test24")
    public class Test24 {
     static final Object room = new Object();
     static boolean hasCigarette = false;
     static boolean hasTakeout = false;
     static ReentrantLock ROOM = new ReentrantLock();
    
     // 等待烟的休息室
     static Condition waitCigaretteSet = ROOM.newCondition();
     // 等外卖的休息室
     static Condition waitTakeoutSet = ROOM.newCondition();
    
     public static void main(String[] args) {
    
         new Thread(() -> {
             ROOM.lock();
             try {
                 log.debug("有烟没?[{}]", hasCigarette);
                 while (!hasCigarette) {
                     log.debug("没烟,先歇会!");
                     try {
                         waitCigaretteSet.await();
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }
                 }
                 log.debug("可以开始干活了");
             } finally {
                 ROOM.unlock();
             }
         }, "小南").start();
    
         new Thread(() -> {
             ROOM.lock();
             try {
                 log.debug("外卖送到没?[{}]", hasTakeout);
                 while (!hasTakeout) {
                     log.debug("没外卖,先歇会!");
                     try {
                         waitTakeoutSet.await();
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }
                 }
                 log.debug("可以开始干活了");
             } finally {
                 ROOM.unlock();
             }
         }, "小女").start();
    
         sleep(1);
         new Thread(() -> {
             ROOM.lock();
             try {
                 hasTakeout = true;
                 waitTakeoutSet.signal();
             } finally {
                 ROOM.unlock();
             }
         }, "送外卖的").start();
    
         sleep(1);
    
         new Thread(() -> {
             ROOM.lock();
             try {
                 hasCigarette = true;
                 waitCigaretteSet.signal();
             } finally {
                 ROOM.unlock();
             }
         }, "送烟的").start();
     }
    }
    
  3. await() 前需要获得锁

  4. await() 执行后,会释放锁,进入 conditionObject 等待
  5. await() 的线程被唤醒(或打断、或超时)取重新竞争 lock 锁,执行唤醒的线程也必须先获得锁
  6. 竞争 lock 锁成功后,从 await() 后继续执行

同步模式之顺序控制

  1. 固定运行顺序,比如,必须先 2 后 1 打印

    1. wait notify 版 ```java @Slf4j(topic = “c.Test25”) public class Test25 { static final Object lock = new Object(); // 表示 t2 是否运行过 static boolean t2runned = false;

      public static void main(String[] args) { Thread t1 = new Thread(() -> {

        synchronized (lock) {
            while (!t2runned) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("1");
        }
      

      }, “t1”);

    Thread t2 = new Thread(() -> {
        synchronized (lock) {
            log.debug("2");
            t2runned = true;
            lock.notify();
        }
    }, "t2");

    t1.start();
    t2.start();
}

}


   2. **Park Unpark 版**
```java
@Slf4j(topic = "c.Test26")
public class Test26 {
    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            LockSupport.park();
            log.debug("1");
        }, "t1");
        t1.start();

        new Thread(() -> {
            log.debug("2");
            LockSupport.unpark(t1);
        },"t2").start();
    }
}
  1. 交替输出,线程 1 输出 a 5 次,线程 2 输出 b 5 次,线程 3 输出 c 5 次。现在要求输出 abcabcabcabcabc 怎么实现

    1. wait notify 版 ```java public class TestWaitNotify {

      public static void main(String[] args) {

      WaitNotify waitNotify = new WaitNotify(1,5);

      new Thread(() -> {

        waitNotify.print("a",1,2); 
      

      },”a线程”).start();

      new Thread(() -> {

        waitNotify.print("b",2,3);
      

      },”b线程”).start();

      new Thread(() -> {

        waitNotify.print("c",3,1);
      

      },”c线程”).start(); } }

class WaitNotify { private int flag; private int loopNumber;

public WaitNotify(int flag, int loopNumber) {
    this.flag = flag;
    this.loopNumber = loopNumber;
}

/*打印*/
public void print(String str ,int waitFlag , int nextFlag){
    for (int i = 0; i < loopNumber; i++) {
        synchronized (this){
            while (waitFlag != this.flag){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.print(str);
            this.flag = nextFlag;
            this.notifyAll();
        }
    }
}

}


   2. **Park Unpark 条件变量 版** 
```java
public class TestParkUnpark {

    static Thread a ;
    static Thread b ;
    static Thread c ;

    public static void main(String[] args) {
        ParkUnpark parkUnpark = new ParkUnpark(5);

        a = new Thread(() -> {
            parkUnpark.print("a",b);
        },"a");

         b = new Thread(() -> {
            parkUnpark.print("b",c);
        },"b");

         c = new Thread(() -> {
            parkUnpark.print("c",a);
        },"c");

        a.start();
        b.start();
        c.start();

        LockSupport.unpark(a);
    }
}

class ParkUnpark {
    private int loopNumber;

    public ParkUnpark(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    public void print(String str,  Thread nextThread){
        for (int i = 0; i < loopNumber; i++) {
            LockSupport.park();
            System.out.print(str);
            LockSupport.unpark(nextThread);
        }
    }
}
  1. ReentrantLock 版(条件变量) ```java public class TestAwaitSignal {

    public static void main(String[] args) throws InterruptedException {

    AwaitSignal awaitSignal = new AwaitSignal(5);

    Condition a_condition = awaitSignal.newCondition(); Condition b_condition = awaitSignal.newCondition(); Condition c_condition = awaitSignal.newCondition();

    new Thread(() -> {

      awaitSignal.print("a", a_condition, b_condition);
    

    },”a”).start();

    new Thread(() -> {

      awaitSignal.print("b", b_condition, c_condition);
    

    },”b”).start();

    new Thread(() -> {

      awaitSignal.print("c", c_condition, a_condition);
    

    },”c”).start();

    Thread.sleep(1000);

    awaitSignal.lock();
    try {
        a_condition.signal();  //首先唤醒a线程
    }finally {
        awaitSignal.unlock();
    }
}

}

class AwaitSignal extends ReentrantLock { private int loopNumber;

public AwaitSignal(int loopNumber) {
    this.loopNumber = loopNumber;
}

public void print(String str, Condition condition, Condition next){
    for (int i = 0; i < loopNumber; i++) {
        lock();

        try{
            condition.await();
            System.out.print(str);
            next.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            unlock();
        }
    }
}

} ```