日出星辰

          解決Join方法的疑惑

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

           假如在main方法中有個線程A,執行了A.join(),那么線程A繼續執行,而main線程這阻塞在A.join()處,直到線程A執行完畢并正常退出,此時main方法中的A.join()才返回,然后繼續執行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是個隨機數,使用n=1000
          }
          System.out.println(
          "n=" + ThreadJoin.n);
          }
          }

           

           

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


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


          網站導航:
           
          主站蜘蛛池模板: 屯昌县| 高安市| 宜章县| 井冈山市| 全州县| 林口县| 织金县| 滨海县| 黄平县| 黑龙江省| 新蔡县| 丹棱县| 台南县| 福建省| 阿城市| 绥滨县| 张北县| 鹿泉市| 临安市| 务川| 廊坊市| 通海县| 伊吾县| 普格县| 贵溪市| 和林格尔县| 乡宁县| 仪陇县| 同江市| 桂阳县| 乌海市| 铜鼓县| 佛冈县| 台北市| 泸溪县| 来宾市| 昭通市| 璧山县| 故城县| 南涧| 泾源县|