一.作用
Thread类中的join方法的主要作用就是同步,它可以使得线程之间的并行执行变为串行执行。在A线程中调用B线程的join方法,A会等待B执行完后,再执行后面的代码。
public static void main(String[] args) throws InterruptedException {
Runnable task=()->{
try {
Thread.sleep(5000);
System.out.println("I am task!");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Thread thread=new Thread(task);
thread.start();
thread.join();
System.out.println("I am main!");
}
二.join与start调用顺序问题
join方法必须在线程start方法调用之后调用才有意义。