看看这个方法Thread#join().例如:
Thread a = ...;
a.start();
a.join(); // wait until Thread a finishes
Run Code Online (Sandbox Code Playgroud)
简单的。使用Thread.join()。当您生成线程时,将它们添加到列表中并遍历该列表并调用 thread.join()。一旦您退出该循环,您的所有线程都被确认已完成。然后您可以在此之后使用打印语句。
像这样的东西:
import java.lang.*;
public class ThreadDemo implements Runnable {
public void run() {
//some implementation here
}
public static void main(String args[]) throws Exception {
List<Thread> threadList = new ArrayList<Thread>();
Thread t1 = new Thread(new ThreadDemo());
t1.start();
threadList.add(t1);
Thread t2 = new Thread(new ThreadDemo());
t2.start();
threadList.add(t2);
for(Thread t : threadList) {
// waits for this thread to die
t.join();
}
System.out.print("All the threads are completed by now");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8456 次 |
| 最近记录: |