Java notify和notifyAll的区别和相同


-
本文主要介绍Java notify和notifyAll的知识,这里整理详细的资料来说明notify 和NotifAll的区别,有需要的小伙伴可以参考下
-
2020-09-01
java 并发基础 notify()与notifyAll() 的理解_course
2019-09-24代码来自java 编程思想第4版 21章 * 代码1 ```java //: concurrency/NotifyVsNotifyAll.java package concurrency; /* Added by Eclipse.py */ import java.util.concurrent.*; import java.util.*; class Blocker { synchronized void waitingCall() { try { while (!Thread.interrupted()) { wait(); System.out.print(Thread.currentThread() + " "); } } catch (InterruptedException e) { // OK to exit this way } } synchronized void prod() { notify(); } synchronized void prodAll() { notifyAll(); } } class Task implements Runnable { static Blocker blocker = new Blocker(); public void run() { blocker.waitingCall(); } } class Task2 implements Runnable { // A separate Blocker object: static Blocker blocker = new Blocker(); public void run() { blocker.waitingCall(); } } public class NotifyVsNotifyAll { public static void main(String[] args) throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++) exec.execute(new Task()); exec.execute(new Task2()); Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { boolean prod = true; public void run() { if (prod) { System.out.print("\nnotify() "); Task.blocker.prod(); prod = false; } else { System.out.print("\nnotifyAll() "); Task.blocker.prodAll(); prod = true; } } }, 400, 400); // Run every .4 second TimeUnit.SECONDS.sleep(5); // Run for a while... timer.cancel(); System.out.println("\nTimer canceled"); TimeUnit.MILLISECONDS.sleep(500); System.out.print("Task2.blocker.prodAll() "); Task2.blocker.prodAll(); TimeUnit.MILLISECONDS.sleep(500); System.out.println("\nShutting down"); exec.shutdownNow(); // Interrupt all tasks } } /* * Output: (Sample) notify() Thread[pool-1-thread-1,5,main] notifyAll() * Thread[pool-1-thread-1,5,main] Thread[pool-1-thread-5,5,main] * Thread[pool-1-thread-4,5,main] Thread[pool-1-thread-3,5,main] * Thread[pool-1-thread-2,5,main] notify() Thread[pool-1-thread-1,5,main] * notifyAll() Thread[pool-1-thread-1,5,main] Thread[pool-1-thread-2,5,main] * Thread[pool-1-thread-3,5,main] Thread[pool-1-thread-4,5,main] * Thread[pool-1-thread-5,5,main] notify() Thread[pool-1-thread-1,5,main] * notifyAll() Thread[pool-1-thread-1,5,main] Thread[pool-1-thread-5,5,main] * Thread[pool-1-thread-4,5,main] Thread[pool-1-thread-3,5,main] * Thread[pool-1-thread-2,5,main] notify() Thread[pool-1-thread-1,5,main] * notifyAll() Thread[pool-1-thread-1,5,main] Thread[pool-1-thread-2,5,main] * Thread[pool-1-thread-3,5,main] Thread[pool-1-thread-4,5,main] * Thread[pool-1-thread-5,5,main] notify() Thread[pool-1-thread-1,5,main] * notifyAll() Thread[pool-1-thread-1,5,main] Thread[pool-1-thread-5,5,main] * Thread[pool-1-thread-4,5,main] Thread[pool-1-thread-3,5,main] * Thread[pool-1-thread-2,5,main] notify() Thread[pool-1-thread-1,5,main] * notifyAll() Thread[pool-1-thread-1,5,main] Thread[pool-1-thread-2,5,main] * Thread[pool-1-thread-3,5,main] Thread[pool-1-thread-4,5,main] * Thread[pool-1-thread-5,5,main] Timer canceled Task2.blocker.prodAll() * Thread[pool-1-thread-6,5,main] Shutting down */// :~ ``` * 代码2 ```java //: concurrency/Restaurant.java package concurrency; /* Added by Eclipse.py */ // The producer-consumer approach to task cooperation. import java.util.concurrent.*; import static net.mindview.util.Print.*; class Meal { private final int orderNum; public Meal(int orderNum) { this.orderNum = orderNum; } public String toString() { return "Meal " + orderNum; } } class WaitPerson implements Runnable { private Restaurant restaurant; public WaitPerson(Restaurant r) { restaurant = r; } public void run() { try { while (!Thread.interrupted()) { synchronized (this) { while (restaurant.meal == null) wait(); // ... for the chef to produce a meal } print("Waitperson got " + restaurant.meal); synchronized (restaurant.chef) { restaurant.meal = null; restaurant.chef.notifyAll(); // Ready for another //这里的notifyAll();/////////////////////// } } } catch (InterruptedException e) { print("WaitPerson interrupted"); } } } class Chef implements Runnable { private Restaurant restaurant; private int count = 0; public Chef(Restaurant r) { restaurant = r; } public void run() { try { while (!Thread.interrupted()) { synchronized (this) { while (restaurant.meal != null) wait(); // ... for the meal to be taken } if (++count == 10) { print("Out of food, closing"); restaurant.exec.shutdownNow(); } printnb("Order up! "); synchronized (restaurant.waitPerson) { restaurant.meal = new Meal(count); restaurant.waitPerson.notifyAll();-////////////// } TimeUnit.MILLISECONDS.sleep(100); } } catch (InterruptedException e) { print("Chef interrupted"); } } } public class Restaurant { Meal meal; ExecutorService exec = Executors.newCachedThreadPool(); WaitPerson waitPerson = new WaitPerson(this); Chef chef = new Chef(this); public Restaurant() { exec.execute(chef); exec.execute(waitPerson); } public static void main(String[] args) { new Restaurant(); } } /* * Output: Order up! Waitperson got Meal 1 Order up! Waitperson got Meal 2 Order * up! Waitperson got Meal 3 Order up! Waitperson got Meal 4 Order up! * Waitperson got Meal 5 Order up! Waitperson got Meal 6 Order up! Waitperson * got Meal 7 Order up! Waitperson got Meal 8 Order up! Waitperson * got Meal 9 * Out of food, closing WaitPerson interrupted Order up! Chef interrupted */// :~ ``` * 问题 1. notifyAll是Object的方法 ---public final native void notifyAll();但不是静态方法 这个在代码1中,为什么没有实例对象就可以直接调用该方法 而在代码2中为什么需要 restaurant.waitPerson.notifyAll() ;如果直接改成notifyAll(); 会报错 ``` Order up! Exception in thread "pool-1-thread-1" java.lang.IllegalMonitorStateException at java.lang.Object.notifyAll(Native Method) at concurrency.Chef.run(Restaurant.java:69) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) ``` 2. 这2种调用的方法有什么区别
notify notifyall 很不理解_course
2010-10-05//代码1 public class TestProducerConsumer { public static void main(String args) { SyncStack ss = new
notify与notifyALL区别?_course
2005-12-10书上是这样解释wati,notify,notifyAll的: wait:告诉当前线程放弃监视器并进入睡眠状态,直到其他线程进入同一监视器并调用notify为止。 notify:唤醒同一对象监视器中调用
notify()和notifyAll()的区别_course
2006-08-18如题, 请不要把JDK文档的内容照搬上来,谢谢。
-
学院
C语言零基础入门(详细讲解)
C语言零基础入门(详细讲解)
-
学院
【布道者】Linux极速入门
【布道者】Linux极速入门
-
博客
centos 7 播放此文件需要 MPEG-4 ACC 解码器…… 问题的解决方案
centos 7 播放此文件需要 MPEG-4 ACC 解码器…… 问题的解决方案
-
下载
4-3接收预备党员公示情况表.doc
4-3接收预备党员公示情况表.doc
-
学院
Galera 高可用 MySQL 集群(PXC v5.7+Hapro)
Galera 高可用 MySQL 集群(PXC v5.7+Hapro)
-
学院
MySQL 事务和锁
MySQL 事务和锁
-
下载
1-3入党申请人谈话记实表.doc
1-3入党申请人谈话记实表.doc
-
下载
3-1确定发展对象征求党员意见会议记录(首页).doc
3-1确定发展对象征求党员意见会议记录(首页).doc
-
博客
vue-H5生成二维码
vue-H5生成二维码
-
下载
5-2预备党员考察记实表4份.doc
5-2预备党员考察记实表4份.doc
-
学院
MySQL 数据库的基本操作(数据完整性约束)
MySQL 数据库的基本操作(数据完整性约束)
-
博客
Django settings.py配置文件详解
Django settings.py配置文件详解
-
博客
玩币居士|3.4比特币重新站上50000上方 新一轮的涨势即将到来
玩币居士|3.4比特币重新站上50000上方 新一轮的涨势即将到来
-
下载
chrome的start.bat
chrome的start.bat
-
下载
5-10预备党员转正表决票汇总表.doc
5-10预备党员转正表决票汇总表.doc
-
下载
C#使用GDAL完成矢量数据导入到Postgis(核心代码)
C#使用GDAL完成矢量数据导入到Postgis(核心代码)
-
博客
大牛期货:何时实现“猪肉自由”?两三年内猪周期见底
大牛期货:何时实现“猪肉自由”?两三年内猪周期见底
-
博客
4.1.20 Flink-流处理框架-Flink中的状态管理之算子状态+键控状态
4.1.20 Flink-流处理框架-Flink中的状态管理之算子状态+键控状态
-
博客
个人所得税退税步骤
个人所得税退税步骤
-
博客
【案例】ABB如何在不停止生产的情况下进行编程?
【案例】ABB如何在不停止生产的情况下进行编程?
-
下载
基于梯形加减速的步进电机控制算法源代码.zip
基于梯形加减速的步进电机控制算法源代码.zip
-
学院
实现 MySQL 读写分离的利器 mysql-proxy
实现 MySQL 读写分离的利器 mysql-proxy
-
学院
华为1+X认证——网络系统建设与运维(初级)
华为1+X认证——网络系统建设与运维(初级)
-
下载
6-2党员推荐入党积极分子推荐票.doc
6-2党员推荐入党积极分子推荐票.doc
-
下载
2-5培养联系人登记表.doc
2-5培养联系人登记表.doc
-
下载
5-7预备党员转正公示(范例).doc
5-7预备党员转正公示(范例).doc
-
博客
springboot源码解析-管中窥豹系列之EnableXXX(十)
springboot源码解析-管中窥豹系列之EnableXXX(十)
-
博客
一篇文章带你了解在线代理ip的节点
一篇文章带你了解在线代理ip的节点
-
学院
MySQL 备份与恢复详解(高低版本 迁移;不同字符集 相互转换;表
MySQL 备份与恢复详解(高低版本 迁移;不同字符集 相互转换;表
-
博客
虽是阿里系却难逃与阿里云厮杀,七牛云上市如何与“大象”共舞?
虽是阿里系却难逃与阿里云厮杀,七牛云上市如何与“大象”共舞?