Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความสำคัญของ wait(), notify() และ notifyAll() ใน Java


เธรดสื่อสารกันผ่าน wait(), notify(), notifyAll() ใน Java เป็น final methods ของคลาส Object เรียกได้เฉพาะในบริบท synchronized เท่านั้น wait() ทำให้เธรดปัจจุบันรอจนกว่าอีกเธรดจะเรียก notify() หรือ notifyAll() สำหรับออบเจ็กต์นั้น notify() ปลุกเธรดเดียว ที่รออยู่บน monitor ของออบเจ็กต์ notifyAll() ปลุกเธรดทั้งหมด ที่รออยู่ เธรดรอโดยการเรียก wait() เมธอดเหล่านี้อาจโยน IllegalMonitorStateException หากเธรดปัจจุบันไม่ใช่เจ้าของ monitor

ไวยากรณ์ wait()

public final void wait() throws InterruptedException

ไวยากรณ์ notify()

public final void notify()

ไวยากรณ์ notifyAll()

public final void notifyAll()

ตัวอย่าง

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(); //waiting, not running
            }
            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();
    }
}

ผลลัพธ์

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