假设我有这个非常简单的代码:
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句