在Java中,join()
方法可能會拋出InterruptedException
異常。當線程在等待另一個線程完成時被中斷,就會拋出這個異常。為了處理這個異常,你需要在調(diào)用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(); // 這里調(diào)用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();
}
}
在這個示例中,我們創(chuàng)建了兩個線程thread1
和thread2
。thread2
試圖調(diào)用thread1
的join()
方法,以便在線程1完成后繼續(xù)執(zhí)行。我們使用try-catch
語句捕獲可能拋出的InterruptedException
異常,并在異常發(fā)生時輸出相應的消息。這樣,我們可以確保程序在遇到異常時能夠正確地處理,而不是崩潰。