在sychronized中咱們可使用wait(),notify()來讓線程等待、喚醒;在ReentrantLock中咱們能夠用Condition中的await(),signal()來實現;ide
public class LockCondition { private static ReentrantLock lock=new ReentrantLock(); private static Condition condition=lock.newCondition(); public static void main(String[] args) { Thread t1=new Thread(new task1(),"task1"); Thread t2=new Thread(new task2(),"task2"); t1.start();t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public static class task1 implements Runnable{ @Override public void run() { lock.lock(); System.out.println(Thread.currentThread().getName()+"開始執行"); System.out.println(Thread.currentThread().getName()+"釋放鎖並等待"); try { condition.await(); System.out.println(Thread.currentThread().getName()+"從新獲取到鎖"); System.out.println(Thread.currentThread().getName()+"執行完成"); } catch (InterruptedException e) { e.printStackTrace(); }finally { lock.unlock(); } } } public static class task2 implements Runnable{ @Override public void run() { lock.lock(); System.out.println(Thread.currentThread().getName()+"開始執行"); System.out.println(Thread.currentThread().getName()+"開始喚醒其餘線程"); condition.signal(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"執行完成"); lock.unlock(); } } } 執行結果以下: task1開始執行 task1釋放鎖並等待 task2開始執行 task2開始喚醒其餘線程 task2執行完成 task1從新獲取到鎖 task1執行完成
解析:task1執行到await()時會釋放lock,task2獲取到鎖,在task2中喚醒task1,但此時lock仍是被task2佔據,故會等到task2執行完成task1纔會拿到lock再繼續執行線程