代码例子:
public static void main(String[] args) throws Exception{
int count = 10;
List<Thread> workers = new ArrayList<>();
for(int i = 0; i < count; i++) {
final int s = i;
Thread worker = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(500);
System.out.println("执行子线程" + s);
}catch (Exception e){
}
}
});
worker.start();
workers.add(worker);
}
for(int i = 0; i < count; i++) {
workers.get(i).join();
}
System.out.println("执行主线程");
}
结果:
执行子线程7
执行子线程6
执行子线程3
执行子线程2
执行子线程9
执行子线程8
执行子线程5
执行子线程4
执行子线程1
执行子线程0
执行主线程
查看jdk中join源码,你会发现,官方翻译是等待线程死亡,也就是线程执行结束
/**
* Waits for this thread to die.
*
* <p> An invocation of this method behaves in exactly the same
* way as the invocation
*
* <blockquote>
* {@linkplain #join(long) join}{@code (0)}
* </blockquote>
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public final void join() throws InterruptedException {
join(0);
}