Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 wait(), notify() 및 notifyAll() 메소드의 중요성?


스레드는 wait(), notify() 를 통해 서로 통신할 수 있습니다. 및 notifyAll() 자바의 메소드. 최종입니다. 객체 에 정의된 메소드 클래스이며 동기화된 내에서만 호출할 수 있습니다. 문맥. 대기() 메소드는 현재 스레드가 다른 스레드가 notify() 를 호출할 때까지 기다리게 합니다. 또는 notifyAll() 해당 객체에 대한 메소드. 알림() 단일 스레드를 깨우는 메소드 그것은 그 개체의 모니터에서 기다리고 있습니다. notifyAll() 모든 스레드를 깨우는 메소드 그 개체의 모니터를 기다리고 있는 것입니다. 스레드는 wait() 중 하나를 호출하여 개체의 모니터를 기다립니다. 방법. 이러한 메소드는 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.