一.作用
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方法调用之后调用才有意义。
本文介绍了Java中Thread类的join方法,解释了它如何使线程同步执行而非并行执行。通过示例代码展示了如何在A线程中调用B线程的join方法,从而使A线程等待B线程执行完毕后再继续执行。
715

被折叠的 条评论
为什么被折叠?



