package com.bjsxt.height.lock020; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class UseCondition { private Lock lock = new ReentrantLock();//Reentrant lock. private Condition condition = lock.newCondition();//Same as wait() and notify methods. public void method1(){ try { lock.lock(); System.out.println("Current thread:" + Thread.currentThread().getName() + "Entering the waiting state.."); Thread.sleep(3000); System.out.println("Current thread:" + Thread.currentThread().getName() + "Release lock.."); condition.await(); // Object wait System.out.println("Current thread:" + Thread.currentThread().getName() + "Continue to execute..."); } catch (Exception e) { e.printStackTrace (); } finally { System.out.println("release lock method1"); lock.unlock(); } } public void method2(){ try { lock.lock(); System.out.println("Current thread:" + Thread.currentThread().getName() + "Enter.."); Thread.sleep(3000); System.out.println("Current thread:" + Thread.currentThread().getName() + "Send wakeup.."); condition.signal(); //Object notify } catch (Exception e) { e.printStackTrace (); } finally { System.out.println("release lock method2"); lock.unlock(); } } public static void main(String[] args) { final UseCondition uc = new UseCondition(); Thread t1 = new Thread(new Runnable() { @Override public void run() { uc.method1(); } }, "t1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { uc.method2(); } }, "t2"); t1.start(); t2.start(); } }