java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is terminated before the next instruction is executed by the program.
解释:调用一个线程对象的join方法,当该线程对象执行完了才会执行join()方法后边的代码。
示例:
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 20; i > 0; i--) {
System.out.println("非主线程执行:" + i);
}
});
thread.start();
System.out.println("主线程输出");
}
不使用join,主线程先执行了,二者没有执行先后关系。
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
for (int i = 20; i > 0; i--) {
System.out.println("非主线程执行:" + i);
}
});
thread.start();
thread.join();
System.out.println("主线程输出");
}
加上join方法,主线程会等待thread对象执行完后再执行join()方法后边的指令。