在A线程中调用了B线程的join()方法时,表示只有当B线程执行完毕时,A线程才能继续执行。
public class JoinDemo {
private static class JoinThread extends Thread{
private String name;
public JoinThread(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i <= 3; i++){
System.out.println(name + " loop " + i);
}
}
}
public static void main(String [] args) throws InterruptedException {
System.out.println("main thread start !");
JoinThread t1 = new JoinThread("A");
JoinThread t2 = new JoinThread("B");
t1.start();
t1.join();
t2.start();
System.out.println("main thread end !");
}
}
本文通过一个简单的Java示例,深入解析了线程同步的概念。在多线程环境中,使用join()方法可以确保一个线程在另一个线程完成后才继续执行,有效避免了线程间的竞争条件,保障了程序的正确运行。
5281

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



