日出星辰

          線程學習筆記【4】---線程之間通信

          子線程先循環10次,然后主線程循環100次,再子線程循環10次,主線程循環100次,就這樣循環往復50次。

          public class Communtion01 {

          public static void main(String args[]) {
          final Bussiness buss = new Bussiness();
          new Thread(new Runnable() {

          public void run() {
          for (int j = 1; j <= 50; j++) {
          buss.sub(j);
          }
          }
          }).start();

          for (int j = 1; j <= 50; j++) {
          buss.main(j);
          }
          }

          }

          class Bussiness {
          private boolean subFlag = true;

          //Cpu照顧sub線程,執行到sub(),但還不該sub執行,那就wait
          public synchronized void sub(int j) {
          while (!subFlag) {
          try {
          this.wait();
          }
          catch (InterruptedException e) {
          e.printStackTrace();
          }
          }
          for (int i = 1; i <= 10; i++) {
          System.out.println(Thread.currentThread().getName()
          + "在第" + j
          + "次循環了" + i);
          }
          subFlag
          = false;
          this.notify();
          }

          public synchronized void main(int j) {
          while(subFlag) {
          try {
          this.wait();
          }
          catch (InterruptedException e) {
          e.printStackTrace();
          }
          }
          for (int i =1; i <=100; i++) {
          System.out.println(Thread.currentThread().getName()
          + "在第" + j
          + "次循環了" + i);
          }
          subFlag
          = true;
          this.notify();
          }
          }

          經驗:要用到共同數據(包括同步鎖)或共同算法的若干方法應該歸在同一個類身上,這種設計體現了高類聚和程序的健壯性。

          互斥、同步、通信問題的邏輯不是寫在線程代碼上,而是在線程訪問那個資源類上。

           

          posted on 2011-08-29 17:31 日出星辰 閱讀(82) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 宝丰县| 曲阜市| 斗六市| 泰宁县| 绥阳县| 黄大仙区| 潞城市| 安康市| 鹰潭市| 云南省| 盐津县| 博客| 鹿泉市| 六安市| 云浮市| 两当县| 南和县| 乌苏市| 大城县| 根河市| 佛坪县| 石楼县| 云龙县| 苍山县| 大同市| 英吉沙县| 湘潭市| 双城市| 河源市| 大连市| 泸州市| 正宁县| 竹山县| 股票| 文登市| 龙门县| 临沧市| 哈密市| 霍州市| 赞皇县| 江源县|