日出星辰

          線程學(xué)習(xí)筆記【4】---線程之間通信

          子線程先循環(huán)10次,然后主線程循環(huán)100次,再子線程循環(huán)10次,主線程循環(huán)100次,就這樣循環(huán)往復(fù)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線程,執(zhí)行到sub(),但還不該sub執(zhí)行,那就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
          + "次循環(huán)了" + 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
          + "次循環(huán)了" + i);
          }
          subFlag
          = true;
          this.notify();
          }
          }

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

          互斥、同步、通信問(wèn)題的邏輯不是寫(xiě)在線程代碼上,而是在線程訪問(wèn)那個(gè)資源類上。

           

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


          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 呼玛县| 海原县| 军事| 隆安县| 商南县| 叶城县| 如皋市| 綦江县| 安徽省| 郎溪县| 车致| 新泰市| 五莲县| 无棣县| 沁源县| 上饶市| 柘荣县| 沁阳市| 蓬莱市| 双城市| 石泉县| 蕲春县| 灯塔市| 盐边县| 海林市| 昌宁县| 静安区| 通海县| 盐山县| 新安县| 元朗区| 台安县| 綦江县| 金塔县| 武义县| 垦利县| 长顺县| 轮台县| 彩票| 花莲县| 朔州市|