public class ThreadJoinExample {
public static void main(String[] args) {
// 创建一个新线程
Thread thread1 = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 1: " + i);
try {
Thread.sleep(100); // 让线程暂停一段时间,模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 创建另一个新线程
Thread thread2 = new Thread(() -> {
try {
System.out.println("Thread 2 is waiting for Thread 1 to finish...");
thread1.join(); // 等待thread1执行完毕
System.out.println("Thread 1 has finished. Thread 2 continues.");
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 2: " + i);
try {
Thread.sleep(100); // 让线程暂停一段时间,模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 启动线程
thread1.start();
thread2.start();
}
}
thread1 和 thread2 是两个独立的线程。thread1 执行一个简单的循环,打印数字并休眠一段时间。thread2 在启动后会调用 thread1.join(),这意味着 thread2 会等待 thread1 完成后再继续执行。thread2 的逻辑在 thread1 完成之后再开始,保证了线程之间的顺序执行。下一篇:java线程池参数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站