2014-11-23 143 views
0

我有兩個線程類:一個打印數字從0到9,另一個從100到109.我想要的是讓第一個線程等待另一個完成。爲此,我使用了join()方法,但它不起作用。請告訴我哪裏出錯:使一個線程等待另一個完成

//demonstrates the use of join() to wait for another thread to finish 
class AThread implements Runnable { 
    Thread t; 

    AThread() { 
     t = new Thread(this); 
    } 

    public void run() { 
     try { 
      for (int i=0; i<10; i++) { 
       System.out.println(i); 
       Thread.sleep(10); 
      } 
     } catch (InterruptedException e) { 
      System.out.println(t + " interruped."); 
     } 
    } 

    public void halt(Thread th) { 
     try { 
      th.join(); 
     } catch (InterruptedException e) { 
      System.out.println(t + " interruped."); 
     } 
    } 
} 

//a different thread class (we distinguish threads by their output) 
class BThread implements Runnable { 
    Thread t; 

    BThread() { 
     t = new Thread(this); 
    } 

    public void run() { 
     try { 
      for (int i=100; i<110; i++) { 
       System.out.println(i); 
       Thread.sleep(10); 
      } 
     } catch (InterruptedException e) { 
      System.out.println(t + " interruped."); 
     } 
    } 
} 

public class WaitForThread { 
    public static void main(String[] args) { 
     AThread t1 = new AThread(); 
     BThread t2 = new BThread(); 

     t1.t.start(); 
     t1.halt(t2.t); //wait for the 100-109 thread to finish 
     t2.t.start(); 
    } 
} 
+0

爲什麼不使用wait()和notify方法實現它?它對於內部線程通信更有意義。 – BatScream 2014-11-23 07:27:05

+0

@BatScream我只是在學習繩索,實際上。 :-) – dotslash 2014-11-23 07:34:15

回答

2

您在線程開始之前調用join。這是行不通的;在這種情況下,join將立即返回,它不會等待另一個線程啓動並稍後停止。您可以在API文檔中看到這一點:

Thread.join()

此實現使用的this.wait電話空調上this.isAlive循環。

Thread.isAlive()

測試線程是否還活着。線程還活着如果它已經啓動並且還沒有死亡。

重新排序報表在main方法

t1.t.start(); 
t2.t.start(); 
t1.halt(t2.t); //wait for the 100-109 thread to finish 

編輯回答您的問題在意見:

如果你想在AThread線程等待在BThread線程在完成工作之前完成,那麼您需要撥打AThread.run中的join,並更改main方法:

class AThread implements Runnable { 
    Thread t; 
    Thread threadToWaitFor; 

    AThread(Thread threadToWaitFor) { 
     t = new Thread(this); 
     this.threadToWaitFor = threadToWaitFor; 
    } 

    public void run() { 
     // First wait for the other thread to finish 
     threadToWaitFor.join(); 

     // ... 
    } 

    // ... 
} 

public class WaitForThread { 
    public static void main(String[] args) { 
     BThread t2 = new BThread(); 
     AThread t1 = new AThread(t2.t); 

     t2.t.start(); 
     t1.t.start(); 
    } 
} 
+0

我重新排列了語句,但兩個線程仍然並行運行。睡眠()方法會導致問題嗎? – dotslash 2014-11-23 07:34:42

+0

不,這是因爲你的代碼的結構。請注意,您實際上使** main **線程等待而不是't1'線程,因爲您正在從主線程調用'join()'。你的代碼沒有做任何事情來阻止線程並行運行。 – Jesper 2014-11-23 07:37:35

+0

嗯......我以爲在t1上打過電話,並且通過t2就足夠了。那我應該怎麼做呢?或者整個'join()'方法不適合? – dotslash 2014-11-23 07:43:11

相關問題