首页 > Java > java教程 > 正文

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

WBOY
发布: 2023-09-04 09:57:06
转载
1401人浏览过

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

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

落笔AI
落笔AI

AI写作,AI写网文、AI写长篇小说、短篇小说

落笔AI 41
查看详情 落笔AI

wait() 方法语法

public final void wait() throws InterruptedException
登录后复制

notify()方法语法

public final void notify()
登录后复制

NotifyAll() 方法语法

public final void notifyAll()<strong>
</strong>
登录后复制

示例

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();
   }
}
登录后复制

输出

Inside start() method
Inside join() method
Waiting for the peer thread to finish.
Inside run() method
Peer thread finished.
登录后复制

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

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号