Condition 将 Object 监视器方法(wait、notify 和 notifyAll)分解成截然不同的对象,以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set(wait-set)。其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。
先看一个关于Condition使用的简单实例:
1 public class ConditionTest { 2 public static void main(String[] args) { 3 final Lock lock = new ReentrantLock(); 4 final Condition condition = lock.newCondition(); 5 6 Thread thread1 = new Thread(new Runnable() { 7 @Override 8 public void run() { 9 try { 10 lock.lock(); 11 System.out.println("我需要等一个信号"+this); 12 condition.await(); 13 System.out.println("我拿到一个信号"+this); 14 } catch (Exception e) { 15 // TODO: handle exception 16 } finally{ 17 lock.unlock(); 18 } 19 20 21 } 22 }, "thread1"); 23 thread1.start(); 24 Thread thread2 = new Thread(new Runnable() { 25 @Override 26 public void run() { 27 try { 28 lock.lock(); 29 System.out.println("我拿到了锁"); 30 Thread.sleep(500); 31 System.out.println("我发出一个信号"); 32 condition.signal(); 33 } catch (Exception e) { 34 // TODO: handle exception 35 } finally{ 36 lock.unlock(); 37 } 38 39 40 } 41 }, "thread2"); 42 thread2.start(); 43 } 44 }
运行结果:
1 我需要等一个信号com.luchao.traditionalthread.ConditionTest$1@10bc3c9 2 我拿到了锁 3 我发出一个信号 4 我拿到一个信号com.luchao.traditionalthread.ConditionTest$1@10bc3c9