標籤:
wait
notify ()
nitifyAll ()
都使用在同步中,因為要對持有監視器(鎖)的線程操作
所以要使用在同步中,因為只有同步才具有鎖
為什麼這些操作線程的方法要定義object類中呢
因為這些方法在操作同步中線程時。都必須要標識他們所操作線程只有的鎖
只有同一個鎖上的被等待線程,可以被同一個鎖上的notify喚醒
不可以對不同鎖中的線程進行喚醒
也就是說,等待和喚醒必須是同一個鎖
而鎖可以使任意對象,所以可以被任意對象調用的方法定義object類中
1 class Res 2 { 3 String name; 4 String sex; 5 boolean flag = false; 6 } 7 8 class Input implements Runnable 9 {10 private Res r ;11 Input (Res r){12 this.r = r;13 }14 public void run (){15 int x = 0;16 while (true)17 {18 synchronized (r) {19 if (r.flag)20 try {r.wait();}catch(Exception e){}21 if (x==0){22 r.name = "java";23 r.sex = "man";24 }25 else26 {27 r.name = "傑克";28 r.sex = "女女vn";29 30 }31 x = (x+1)%2;32 r.flag = true;33 r.notify();34 35 }36 }37 38 } 39 40 }41 42 43 44 class Output implements Runnable45 {46 private Res r; 47 Output (Res r){48 49 this.r = r;50 }51 public void run (){52 while (true){53 synchronized(r){54 55 if (!r.flag)56 57 try {r.wait();}catch (Exception e){}58 System.out.println (r.name+"..."+r.sex);59 r.flag = false;60 r.notify();61 62 }63 }64 65 }66 67 }68 69 public class InputOutputDemo {70 71 public static void main(String[] args) {72 // TODO Auto-generated method stub73 74 System.out.println ("ddddd");75 Res r = new Res ();76 Input input = new Input (r);77 Output output = new Output (r);78 79 80 Thread t1 = new Thread (input);81 Thread t2 = new Thread (output);82 t1.start();83 t2.start();84 }85 86 }
java 中多線程之間的通訊之等待喚醒機制