wait()方法是Java中的一個同步機制,用于讓當前線程等待,直到其他線程調用同一個對象的notify()或notifyAll()方法。wait()方法通常與synchronized關鍵字和synchronized塊一起使用,以確保線程安全。
以下是wait()方法的基本用法:
synchronized關鍵字修飾方法或代碼塊。wait()方法讓當前線程等待。調用wait()方法時,當前線程會釋放對象的鎖,進入等待狀態。notify()或notifyAll()方法時,等待的線程會被喚醒。被喚醒的線程需要重新獲取對象的鎖,然后繼續執行。下面是一個簡單的示例:
public class WaitNotifyExample {
    private static final Object lock = new Object();
    private static boolean ready = false;
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                System.out.println("Thread 1: Waiting for the other thread to set the ready flag.");
                try {
                    lock.wait(); // 當前線程進入等待狀態
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 1: The ready flag is set, and I can continue.");
            }
        });
        Thread t2 = new Thread(() -> {
            synchronized (lock) {
                try {
                    Thread.sleep(2000); // 等待2秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 2: Setting the ready flag.");
                ready = true;
                lock.notify(); // 喚醒等待的線程
            }
        });
        t1.start();
        t2.start();
    }
}
在這個示例中,我們有兩個線程t1和t2。t1線程等待另一個線程t2設置ready標志。t2線程在等待2秒后設置ready標志,并通過調用lock.notify()喚醒等待的線程。當t1線程被喚醒后,它會繼續執行并打印出相應的消息。