2011-11-27 41 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)但保证服务不能被重新配置为使用多个线程。

相关问题