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 }
運行結果:
