>  기사  >  Java  >  Java에서 wait(), inform() 및 informAll() 메소드의 중요성은 무엇입니까?

Java에서 wait(), inform() 및 informAll() 메소드의 중요성은 무엇입니까?

WBOY
WBOY앞으로
2023-09-04 09:57:061285검색

Java에서 wait(), inform() 및 informAll() 메소드의 중요성은 무엇입니까?

스레드는 Java의 wait(), inform() notifyAll() 메소드를 통해 서로 통신할 수 있습니다. 이는 Object 클래스에 정의된 최종 메서드이며 동기화된 컨텍스트에서만 호출할 수 있습니다. wait() 메서드는 다른 스레드가 객체의 notify() 또는 notifyAll() 메서드를 호출할 때까지 현재 스레드를 기다리게 합니다. notify() 메소드 는 이 객체의 모니터를 기다리고 있는 단일 스레드 를 깨웁니다. notifyAll() 메소드 는 이 객체의 모니터를 기다리고 있는 모든 스레드 를 깨웁니다. 스레드는 wait() 메서드 중 하나를 호출하여 개체의 모니터를 기다립니다. 현재 스레드가 개체 모니터의 소유자가 아닌 경우 이러한 메서드는 IllegalMonitorStateException을 발생시킬 수 있습니다.

wait() 메서드 구문

public final void wait() throws InterruptedException

notify() 메서드 구문

public final void notify()

NotifyAll() 메서드 구문

public final void notifyAll()<strong>
</strong>

example

public class WaitNotifyTest {
   private static final long SLEEP_INTERVAL<strong> </strong>= 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();
   }
}

output

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

위 내용은 Java에서 wait(), inform() 및 informAll() 메소드의 중요성은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제