java中傳統的線程通訊個人見解

來源:互聯網
上載者:User

  有一個使用共同資料的經驗:要用到共同資料(包括同步鎖)的若干方法,要放到同一個類裡。體現了程式的高內聚,也增強了程式的健壯性。

 還有一個經驗,把同步代碼或在和鎖放到共同使用的資料上,而不是放線上程內,這樣的好處是什麼呢:首先是更符合物件導向的思想。其次是這種設計結構非常容易實現線程的同步,並且增加線程訪問共同資料的時候不用每次都線上程內增加同步代碼。有利於擴充和維護。

首先看一個例子,子線程先迴圈10次,主線程再迴圈100次,接著子線程迴圈10次,主線程再迴圈100次,如此迴圈往複50次;

實現代碼如下:

public class TraditionalThreadConnection {/** * @param args */public static void main(String[] args) {final Service service = new Service();//子線程new Thread(new Runnable(){@Overridepublic void run() {for(int i = 1;i<=50;i++){service.subThread(i);}}}).start(); //主線程for(int i = 1;i<=50;i++){service.mainThread(i);}}}class Service{/* 是否該子線程啟動並執行標誌 */private boolean isSub = true;public synchronized void subThread(int loop){//首先是判斷是否該子線程運行,不是就等待while(!isSub){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}for(int i=1;i<=10;i++){System.out.println("sub-thread-" + i + ",loop--" + loop);}isSub = false;//子線程運行完之後叫醒主線程this.notify();}public synchronized void mainThread(int loop){while(isSub){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}for(int i=1;i<=100;i++){System.out.println("main-thread-" + i + ",loop--" + loop);}isSub = true;this.notify();}}

還有一點要注意的地方,就在判斷是否等待的地方為什麼用到while而不是if:原因是這樣的,因為使用wait的時候有可能在沒有調用notify的時候自己就喚醒了,開始去執行代碼了,這叫做假喚醒。使用while就可以避免偽喚醒帶來的災難,還可以判斷一下是否可以去執行代碼。

聯繫我們

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