Java多线程同步问题:join()方法应用示例
在Java多线程编程中,join()
方法主要用于等待一个线程执行完毕后再继续执行。以下是一个使用join()
方法的示例:
- 创建两个线程(子类Thread),一个负责打印”Hello from Thread 1!”,另一个负责相同的操作。
public class PrintExample extends Thread {
@Override
public void run() {
System.out.println("Hello from Thread " + this.getName());
}
}
public class JoinDemo {
public static void main(String[] args) {
// 创建打印线程1
PrintExample thread1 = new PrintExample();
thread1.setName("Thread 1");
// 创建打印线程2
PrintExample thread2 = new PrintExample();
thread2.setName("Thread 2");
// 启动两个线程
thread1.start();
thread2.start();
// 线程1执行完毕后,通过join()方法等待
try {
thread1.join(); // 等待Thread 1执行完毕
System.out.println("Both threads have finished execution.");
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Join operation interrupted by InterruptedException.");
}
}
}
在这个示例中,创建了两个打印线程(子类PrintExample),每个线程负责打印一条信息。主线程通过join()
方法等待线程1执行完毕后再继续执行。
当所有操作完成后,程序会输出一条总结信息。
还没有评论,来说两句吧...