![](/img/trans.png)
[英]Java Wait for thread(in another class) to finish before executing code in activity
[英]How to wait for a thread to finish before another thread starts in Java/Android?
假设我有这个非常简单的代码:
for(int i = 0; i < 10; i++) {
thread = new Thread(this);
thread.start();
}
但是,在此代码中,线程显然一次启动10次,并且在前一个完成之前不会等待。 在让线程再次启动之前,如何检查线程是否完成?
在回答您的问题之前,我强烈建议您查看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();
如果每个线程在启动之前必须等待前一个线程完成,那么最好有一个唯一的线程按顺序执行10次原始run方法:
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
OuterClass.this.run();
}
}
}
new Thread(r).start();
只是详细说明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)
但确保无法将服务重新配置为使用多个线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.