Java中的wait(),notify()和notifyAll()方法的重要性?

线程可以通过Java中的wait(),notify()和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()

示例

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("等待对等线程完成。");
            wait(); //waiting, not running
         }
         print("对等线程完成。");
      }
   }
   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
等待对等线程完成。
Inside run() method
对等线程完成。