2011-11-27 74 views
17

比方說,我有一個非常簡單的代碼:如何等待線程在另一個線程以Java/Android啓動之前完成?

for(int i = 0; i < 10; i++) { 
    thread = new Thread(this); 
    thread.start(); 
} 

然而,在這段代碼中,線程顯然是一次開始的10倍和前一個完成之前它不會等待。在讓線程重新啓動之前,如何檢查線程是否完成?

+3

爲什麼你開始一個線程,如果你不想做任何事情,直到該線程完成?只做一個常規的方法調用會更容易,在調用完成之前它不會返回。 – goto10

+0

似乎重複:https://stackoverflow.com/questions/289434/how-to-make-a-java-thread-wait-for-another-threads-output –

回答

30

在回答您的問題之前,我強烈建議您查看ExecutorServices,例如ThreadPoolExecutor

現在回答你的問題:如果你要等待前一個線程來完成,在你開始下之前,你之間添加thread.join()

for(int i = 0; i < 10; i++) { 
    thread = new Thread(this); 
    thread.start(); 

    thread.join(); // Wait for it to finish. 
} 

如果您想要開啓10個線程,讓他們完成他們的工作,然後繼續,你在他們之後循環:

Thread[] threads = new Thread[10]; 
for(int i = 0; i < threads.length; i++) { 
    threads[i] = new Thread(this); 
    threads[i].start(); 
} 

// Wait for all of the threads to finish. 
for (Thread thread : threads) 
    thread.join(); 
+0

這使主線程等待,直到啓動的線程完成。如果我理解正確,OP希望每個啓動的線程都等待,直到前一個完成。 –

+1

另一方面,如果他打算按順序做10件事,他爲什麼首先創建10個線程呢? – aioobe

+0

是的,這就是我的答案。 –

11

如果每一個線程必須等待前一個開始之前完成,你最好有執行原來的運行方法的10倍序列中一個獨特的主題:

Runnable r = new Runnable() { 
    public void run() { 
     for (int i = 0; i < 10; i++) { 
      OuterClass.this.run(); 
     } 
    } 
} 
new Thread(r).start(); 
2

只是爲了闡述aioobe的建議:

在回答您的問題之前,我強烈建議您查看ExecutorServices,例如ThreadPoolExecutor。

有一個特別的ExecutorService可以用於此任務:

ExecutorService pool = Executors.newSingleThreadExecutor(); 
for (int i=0; i<10; i++) { 
    pool.submit(this); //assuming this is a Runnable 
} 
pool.shutdown(); //no more tasks can be submitted, running tasks are not interrupted 

newSingleThreadExecutor()類似於調用newFixedThreadPool(1)但保證服務不能被重新配置爲使用多個線程。

相關問題