wait()
方法本身不會導致異常,但它可能會拋出 InterruptedException
。當你調用一個對象的 wait()
方法時,當前線程會釋放該對象的鎖并進入等待狀態,直到其他線程調用該對象的 notify()
或 notifyAll()
方法喚醒它。在這個過程中,如果其他線程中斷了當前等待的線程,那么 wait()
方法就會拋出 InterruptedException
。
以下是一個簡單的示例:
public class WaitExample {
public static void main(String[] args) {
final Object lock = new Object();
Thread thread = new Thread(() -> {
try {
System.out.println("Thread is waiting...");
lock.wait(); // 調用 wait() 方法,當前線程會釋放鎖并進入等待狀態
System.out.println("Thread is awake!");
} catch (InterruptedException e) {
System.out.println("Thread was interrupted!");
}
});
thread.start();
try {
Thread.sleep(2000); // 讓線程等待一段時間
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Notifying the thread...");
lock.notify(); // 喚醒等待的線程
}
}
在這個示例中,wait()
方法不會導致異常,但如果其他線程中斷了等待的線程,wait()
方法會拋出 InterruptedException
。