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

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


ชุดข้อความสามารถสื่อสารกันได้ผ่าน รอ() แจ้ง() และ notifyAll() เมธอดใน Java นี่คือ สุดท้าย วิธีการที่กำหนดไว้ใน วัตถุ และสามารถเรียกได้จากภายใน ซิงโครไนซ์ . เท่านั้น บริบท. รอ() วิธีทำให้เธรดปัจจุบันรอจนกว่าเธรดอื่นจะเรียกใช้ notify() หรือ notifyAll() วิธีการสำหรับวัตถุนั้น แจ้ง() เมธอด ปลุกเธรดเดียว ที่เฝ้าติดตามวัตถุนั้นอยู่ notifyAll() เมธอด ปลุกเธรดทั้งหมด ที่กำลังรอมอนิเตอร์ของวัตถุนั้น เธรดรอการตรวจสอบของวัตถุโดยเรียกหนึ่งใน รอ() กระบวนการ. วิธีการเหล่านี้สามารถโยน IllegalMonitorStateException หากเธรดปัจจุบันไม่ใช่เจ้าของมอนิเตอร์ของอ็อบเจ็กต์

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.