多線程並發之線程間的通訊,notify,wait__java核心知識學習

來源:互聯網
上載者:User
1.需求:

子線程迴圈10次,主線程迴圈100次,這樣間隔迴圈50次. 2.實現:

package com.amos.concurrent;/** * @ClassName: ThreadSynchronizedConnect * @Description: 用wait,notify實現線程間的通訊,需求:子線程迴圈10次,主線程迴圈100次,這樣間隔迴圈50次. * @author: amosli * @email:hi_amos@outlook.com * @date Apr 20, 2014 4:39:44 PM */public class ThreadSynchronizedConnect {    public static void main(String[] args) {        final Business business = new Business();        new Thread(new Runnable() {            public void run() {                for (int i = 0; i < 50; i++) {                    business.sub(i);                }            }        }).start();        for (int i = 0; i < 50; i++) {            business.main(i);        }    }    /*     * 經驗:要用到共同資料(包括同步鎖)的若干方法,應該歸在同一個類身上,這樣方便實現,高類聚和程式的健狀性上.     */    static class Business {        private boolean is_sub = true;        //子方法        public synchronized void sub(int i) {            while (!is_sub) {//如果不為true,將等待,Blocked狀態                try {                    this.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            for (int j = 0; j < 10; j++) {                System.out.println("sub thread:" + j + "  loop:" + i);            }            is_sub=false;            this.notify();//喚醒正在等待的線程        }        //主方法        public synchronized void main(int i) {            while (is_sub) {                try {                    this.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            for (int j = 0; j < 100; j++) {                System.out.println("main thread:" + j + "  loop:" + i);            }            is_sub=true;            this.notify();        }    }}
3.註解:

這裡要注意的是如果要用到共同資料(包括同步鎖)的若干方法,應該歸在同一個類身上.

1).從線程的四種狀態之間的轉換圖可能看到,將一個線程從可運行狀態轉為阻塞狀態只需要調用wait()方法,即將線程加入到等待狀態.

2).然後將等待中的狀態喚醒只需要調用notify()方法即可,如果要喚醒所有等待中的線程,可以調用notifyall()方法.

3)使用synchronized關鍵字來同步方法,使其在運行時不受影響.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.