如何在Java / Android中另一个线程启动之前等待线程完成?

时间:2011-11-27 19:09:47

标签: java android multithreading loops

假设我有这么简单的代码:

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

但是,在此代码中,线程显然一次启动10次,并且在前一个完成之前不会等待。在让线程重新开始之前,如何检查线程是否完成?

3 个答案:

答案 0 :(得分:32)

在回答您的问题之前,我强烈建议您查看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个线程,让他们完成他们的工作,然后在循环之后继续你join

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();

答案 1 :(得分:11)

如果每个线程必须等到前一个线程在开始之前完成,你最好有一个唯一的线程按顺序执行10次原始run方法:

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

答案 2 :(得分: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),但确保无法将服务重新配置为使用多个线程。

相关问题