微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Java中,wait()、notify()和notifyAll()方法的重要性是什么?

在Java中,wait()、notify()和notifyAll()方法的重要性是什么?

线程之间可以通过 Java 中的 wait()、notify() notifyAll() 方法相互通信。这些是在Object类中定义的最终方法,只能从同步上下文中调用wait() 方法会导致当前线程等待,直到另一个线程调用该对象的 notify() notifyAll() 方法notify() 方法唤醒正在等待该对象监视器的单个线程notifyAll() 方法唤醒所有正在等待该对象监视器的线程。线程通过调用 wait() 方法之一来等待对象的监视器。如果当前线程不是对象监视器的所有者,这些方法可能会抛出 IllegalMonitorStateException

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.

以上就是在Java中,wait()、notify()和notifyAll()方法的重要性是什么?的详细内容,更多请关注编程之家其它相关文章

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐