Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Tầm quan trọng của wait(), notify() và notifyAll() trong Java?

Các luồng giao tiếp với nhau thông qua wait(), notify() và notifyAll() trong Java. Đây là các phương thức final định nghĩa trong lớp Object và chỉ được gọi từ trong ngữ cảnh synchronized. wait() làm luồng hiện tại chờ cho đến khi luồng khác gọi notify() hoặc notifyAll() cho đối tượng đó. notify() thức dậy một luồng đang chờ trên monitor của đối tượng. notifyAll() thức dậy tất cả luồng đang chờ. Luồng chờ trên monitor của đối tượng bằng cách gọi một trong các phương thức wait(). Các phương thức này ném IllegalMonitorStateException nếu luồng hiện tại không phải chủ sở hữu monitor của đối tượng.

Cú pháp wait()

public final void wait() throws InterruptedException

Cú pháp notify()

public final void notify()

Cú pháp notifyAll()

public final void notifyAll()

Ví dụ

public class WaitNotifyTest { 
    private static final long SLEEP_INTERVAL = 3000; 
    private boolean running = true; 
    private Thread thread; 
    
    public void start() { 
        print("Inside start() method"); 
        thread = new Thread(new Runnable() { 
            @Override 
            public void run() { 
                print("Inside run() method"); 
                try { 
                    Thread.sleep(SLEEP_INTERVAL); 
                } catch(InterruptedException e) { 
                    Thread.currentThread().interrupt(); 
                } 
                synchronized(WaitNotifyTest.this) { 
                    running = false; 
                    WaitNotifyTest.this.notify(); 
                } 
            } 
        }); 
        thread.start(); 
    } 
    
    public void join() throws InterruptedException { 
        print("Inside join() method"); 
        synchronized(this) { 
            while(running) { 
                print("Waiting for the peer thread to finish."); 
                wait(); // chờ, không chạy 
            } 
            print("Peer thread finished."); 
        } 
    } 
    
    private void print(String s) { 
        System.out.println(s); 
    } 
    
    public static void main(String[] args) throws InterruptedException { 
        WaitNotifyTest test = new WaitNotifyTest(); 
        test.start(); 
        test.join(); 
    } 
}

Kết quả

Inside start() method Inside join() method Waiting for the peer thread to finish. Inside run() method Peer thread finished.