Thread.join使用场景:
如下例子,有一个任务需要花10秒才完成,现可分2个线程各做一半任务,
2个线程同时跑,5秒后即可完成任务并得到结果。
所以join可应用于,需要多线程执行任务以减少主线程花费时间的场景。
public class ThreadJoin {
public static void main(String[] args) throws InterruptedException {
final List list = new ArrayList();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
list.add("a");
System.out.println("list add a");
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
list.add("b");
System.out.println("list add b");
}
});
t1.start();
t2.start();
//main线程阻塞,直至t1线程执行完毕
t1.join();
//main线程阻塞,直至t2线程执行完毕
t2.join();
System.out.println("list.size : " + list.size());
}
}
输出:
list add a
list add b
list.size : 2