java多線程——線程間通訊之線程等待喚醒機制

來源:互聯網
上載者:User

標籤: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多線程——線程間通訊之線程等待喚醒機制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.