日出星辰

          線程學習筆記【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)  編輯  收藏


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


          網站導航:
           
          主站蜘蛛池模板: 汝南县| 图片| 盐城市| 高邮市| 辛集市| 新郑市| 大兴区| 凤凰县| 大同市| 拉萨市| 特克斯县| 建阳市| 全椒县| 宁化县| 阳春市| 禄丰县| 江永县| 衡山县| 枞阳县| 浮山县| 同仁县| 呈贡县| 黔江区| 南召县| 阿城市| 鄂伦春自治旗| 南充市| 西丰县| 阳泉市| 开江县| 长宁区| 留坝县| 邛崃市| 邯郸市| 乐陵市| 海原县| 天台县| 泸水县| 景泰县| 大庆市| 禹城市|