標籤:wait notify
- 三個方法
wait()
notify()
notifyAll()
三個方法都使用在同步中,因為要對持有鎖(又叫監控)的線程操作。
所以要使用在同步中,因為只有同步才具有鎖。
- 為什麼這些操作線程的方法均出現在Object類中?
因為這些方法在操作同步中的線程時候,都必須要標識所操作線程識有鎖。只有同一個鎖上的被等待的線程,可以被同一個鎖上的notify喚醒,不可以對不同鎖中的線程進行喚醒。
也就是說,等待和喚醒必須是同一個鎖。
public class Demo1 { public static void main(String[] args) { Res res = new Res(); Input i = new Input(res); Output o = new Output(res); Thread t1 = new Thread(i); Thread t2 = new Thread(o); t1.start(); t2.start(); }}class Res { private String name; private String gender; private boolean flag; public synchronized void setNameGender(String name, String gender) { if (flag) try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.name = name; this.gender = gender; this.flag = true; this.notify(); } public synchronized void out() { if (!this.flag) try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(this.name + " : " + this.gender); this.flag = false; this.notify(); }}class Input implements Runnable { private Res res; Input(Res res) { this.res = res; } public void run() { int x = 0; while (true) { if (x % 3 == 0) { res.setNameGender("T-mac", "male"); } else if (x % 3 == 1) { res.setNameGender("麥迪", "男人"); } else { res.setNameGender("CBA", "糟糕"); } x++; } }}class Output implements Runnable { private Res res; Output(Res res) { this.res = res; } public void run() { while (true) { res.out(); } }}
java多線程——線程間通訊之線程等待喚醒機制