日出星辰

          解決Join方法的疑惑

           很長時(shí)間對join方法感到疑惑,不明白到底是誰要阻塞,誰要繼續(xù)執(zhí)行(線程這部分亟需加強(qiáng))。今天和一網(wǎng)友交流后疑惑得到解決,在此表示感謝Stephen_Liu

           假如在main方法中有個線程A,執(zhí)行了A.join(),那么線程A繼續(xù)執(zhí)行,而main線程這阻塞在A.join()處,直到線程A執(zhí)行完畢并正常退出,此時(shí)main方法中的A.join()才返回,然后繼續(xù)執(zhí)行A.join()后面的代碼。

          public class ThreadJoin extends Thread {
          public static int n = 0;

          static synchronized void inc() {
          n
          ++;
          }

          public void run() {
          try {
          for (int i = 0; i < 10; i++) {
          inc();
          sleep(
          3);
          }
          }
          catch (InterruptedException e) {
          e.printStackTrace();
          }
          }

          public static void main(String[] args) throws Exception {
          Thread thread[]
          = new Thread[100];
          for (int i = 0; i < thread.length; i++) {
          thread[i]
          = new ThreadJoin();
          }
          for (int i = 0; i < thread.length; i++) {
          thread[i].start();
          }
          for (int i = 0; i < thread.length; i++) {
          thread[i].join();
          //不使用這句話n是個隨機(jī)數(shù),使用n=1000
          }
          System.out.println(
          "n=" + ThreadJoin.n);
          }
          }

           

           

          posted on 2011-08-23 20:57 日出星辰 閱讀(62) 評論(0)  編輯  收藏


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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 邢台市| 旺苍县| 漾濞| 建宁县| 灵川县| 金湖县| 泸西县| 高邑县| 梓潼县| 离岛区| 安庆市| 德庆县| 尼玛县| 汶上县| 嘉祥县| 石首市| 鹤峰县| 枝江市| 诏安县| 汶上县| 平泉县| 慈溪市| 陵川县| 宁夏| 通化市| 望都县| 江津市| 武义县| 渭源县| 郸城县| 尚义县| 镇原县| 清流县| 临澧县| 武清区| 宣城市| 遂溪县| 扎囊县| 庆城县| 漾濞| 柯坪县|