在Java中,join()
方法可能会抛出InterruptedException
异常。当线程在等待另一个线程完成时被中断,就会抛出这个异常。为了处理这个异常,你需要在调用join()
方法的地方使用try-catch
语句。下面是一个简单的示例:
public class JoinExceptionExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
try {
System.out.println("Thread 1 is running.");
Thread.sleep(2000);
System.out.println("Thread 1 is finished.");
} catch (InterruptedException e) {
System.out.println("Thread 1 was interrupted.");
}
});
Thread thread2 = new Thread(() -> {
try {
System.out.println("Thread 2 is running.");
thread1.join(); // 这里调用thread1的join()方法,可能会抛出InterruptedException
System.out.println("Thread 2 is finished.");
} catch (InterruptedException e) {
System.out.println("Thread 2 was interrupted while waiting for Thread 1.");
}
});
thread2.start();
}
}
在这个示例中,我们创建了两个线程thread1
和thread2
。thread2
试图调用thread1
的join()
方法,以便在线程1完成后继续执行。我们使用try-catch
语句捕获可能抛出的InterruptedException
异常,并在异常发生时输出相应的消息。这样,我们可以确保程序在遇到异常时能够正确地处理,而不是崩溃。