兩個線程用object1
作 wait/notify
, 是這樣:java
thread1 獲得object1 的 monitor, 調用 object1.wait() - 釋放object1 的 monitor, thread1 wait; thread2 獲得 object1 的 monitor, 調用 object1.notify() - 激活thread1, 釋放object1 的 monitor; thread1 獲得 object1 的 monitor, 從object1.wait()返回, thread1接着執行.
舉例子:this
public class TestWaitNotify { public static void main(String[] args) throws Exception { Object object = new Object(); TestWaitNotify t = new TestWaitNotify(); new Thread(new TaskWait(object),"thread1").start(); new Thread(new TaskWait(object),"thread2").start(); } } class TaskWait implements Runnable { Object object; public TaskWait(Object object) { this.object = object; } public void run() { try { synchronized (object) { System.out.println(Thread.currentThread().getName()); // object.wait(); Thread.currentThread().sleep(10000); } }catch (InterruptedException e){ } } } 輸出結果是: thread1 ..等待10s thread2
若是把object.wait()的註釋放開呢?線程
public class TestWaitNotify { public static void main(String[] args) throws Exception { Object object = new Object(); TestWaitNotify t = new TestWaitNotify(); new Thread(new TaskWait(object), "thread1").start(); new Thread(new TaskWait(object), "thread2").start(); } } class TaskWait implements Runnable { Object object; public TaskWait(Object object) { this.object = object; } public void run() { try { synchronized (object) { System.out.println(Thread.currentThread().getName()); object.wait(); Thread.currentThread().sleep(10000); } } catch (InterruptedException e) { } } } 輸出結果是: thread1 thread2
對比二者,只要調用了wait方法,線程會阻塞,但也放棄了對象鎖。code
此外,Condition的await方法也是同樣的狀況對象
public class TestCondition { public static void main(String[] args) throws Exception { Lock lock = new ReentrantLock(); Condition condition = lock.newCondition(); new Thread(new Blockq(lock,condition),"thread1").start(); new Thread(new Blockq(lock,condition),"thread2").start(); } } class Blockq implements Runnable { Lock lock; Condition condition; public Blockq(Lock lock, Condition condition) { this.lock = lock; this.condition = condition; } public void run() { lock.lock(); try { System.out.println(Thread.currentThread().getName()); //condition.await(); Thread.currentThread().sleep(10000); } catch (InterruptedException e) { } finally { lock.unlock(); } } }