我正在实现Java的Runnable
接口进行多线程编程。我有一些线程,假设有n
个。每个线程都有自己的生命周期。我想等待所有线程的生命周期结束。比如下面这种情况:
for(int i = 0; i< k;i++){
Thread thread1 = new Thread(new xyz())
Thread thread2 = new Thread(new abc())
Thread thread3 = new Thread(new mno())
thread1.start();
thread2.start();
thread3.start();
}
我正在执行以下操作以进行同步。 我不知道是否正确。 请告诉我该如何做? 是否有任何方法可以检查我的线程程序是否正常工作?
if(thread2.isAlive())
try {
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(thread1.isAlive())
try {
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(thread3.isAlive())
try {
thread3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
awaitTermination
的返回值并循环执行是个好主意,以防它花费的时间超过你指定的时间。 - OldCurmudgeonawaitTermination(Long.MAX_VALUE, ...)
而不是只等待60秒。 - Gray