一:概念java
線程通訊中常常用到wait和notify,顧名思義,wait即讓當前線程處於等待狀態,notify通知鎖對象線程
上的另外一個線程被喚醒,這裏的喚醒是指能夠去爭奪鎖資源,nofityAll是喚醒該對象上面全部處於對象
wait狀態的線程blog
二:示例資源
線程t2一運行就處於wait等待狀態,而後線程t1運行notify,喚醒線程t2get
/** * */ package com.day2; /** * @author Administrator * */ public class NotifyWaitThreadDemo { private int count; public static void main(String[] args) { NotifyWaitThreadDemo demo = new NotifyWaitThreadDemo(); Thread t1 = new Thread("t1") { public void run() { synchronized (demo) { for (int i = 0; i < 100; i++) { demo.count = i; if (demo.count == 50) { System.out.println(Thread.currentThread().getName()+"發出通知"); demo.notify(); } } } } }; Thread t2 = new Thread("t2") { public void run() { while (true) { synchronized (demo) { System.out.println(Thread.currentThread().getName() + "開始等待"); try { demo.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "跳出等待"); System.out.println("demo.count" + demo.count); break; } } }; t2.start(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } t1.start(); } }
若是還有一個線程t3也處於wait狀態,那麼t1線程若是想喚醒t1和t3,就須要使用notifyAllit
/** * */ package com.day2; /** * @author Administrator * */ public class NotifyWaitThreadDemo { private int count; public static void main(String[] args) { NotifyWaitThreadDemo demo = new NotifyWaitThreadDemo(); Thread t1 = new Thread("t1") { public void run() { synchronized (demo) { for (int i = 0; i < 100; i++) { demo.count = i; if (demo.count == 50) { System.out.println(Thread.currentThread().getName()+"發出通知"); //demo.notify(); demo.notifyAll(); } } } } }; Thread t2 = new Thread("t2") { public void run() { while (true) { synchronized (demo) { System.out.println(Thread.currentThread().getName() + "開始等待"); try { demo.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "跳出等待"); System.out.println("demo.count" + demo.count); break; } } }; Thread t3 = new Thread("t3") { public void run() { while (true) { synchronized (demo) { System.out.println(Thread.currentThread().getName() + "開始等待"); try { demo.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "跳出等待"); break; } } }; t2.start(); t3.start(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } t1.start(); } }
運行結果:io
t2開始等待 t3開始等待 t1發出通知 t3跳出等待 t2跳出等待 demo.count99