某汽车电商行业面试(怎样使得Java主线程等待所有子线程执行完毕再执行)
如何让所有的子线程执行完毕再执行主线程呢。一般的有如下方法:
1、 让主线程等待,或着睡眠几分钟。用Thread.sleep()或者TimeUnit.SECONDS.sleep(5);但是这个方法时间不好把控,不建议用这个方式
package andy.thread.traditional.test;
import java.util.concurrent.TimeUnit;
public class ThreadSubMain1 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
// 模拟子线程任务
} catch (InterruptedException e) {
}
System.out.println("子线程" + Thread.currentThread() + "执行完毕");
}
}).start();
}
try {
// 等待全部子线程执行完毕
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("主线执行。");
}
}
2、
使用Thread的join()等待所有的子线程执行完毕,主线程在执行
实现 如下:
package andy.thread.traditional.test;
import java.util.Vector;
public class ThreadSubMain2 {
public static void main(String[] args) {
// 使用线程安全的Vector
Vector<Thread> threads = new Vector<Thread>();
for (int i = 0; i < 10; i++) {
Thread iThread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
// 模拟子线程任务
} catch (InterruptedException e) {
}
System.out.println("子线程" + Thread.currentThread() + "执行完毕");
}
});
threads.add(iThread);
iThread.start();
}
for (Thread iThread : threads) {
try {
// 等待所有线程执行完毕
iThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("主线执行。");
}
}