基于Java多线程notify与notifyall的区别分析
当一个线程进入wait之后,就必须等其他线程notify/notifyall,使用notifyall,可以唤醒
所有处于wait状态的线程,使其重新进入锁的争夺队列中,而notify只能唤醒一个。注意,任何时候只有一个线程可以获得锁,也就是说只有一个线程可以运行synchronized 中的代码,notifyall只是让处于wait的线程重新拥有锁的争夺权,但是只会有一个获得锁并执行。
那么notify和notifyall在效果上又什么实质区别呢?
主要的效果区别是notify用得不好容易导致死锁,例如下面提到的例子。
public synchronized void put(object o) {
while (buf.size()==max_size) {
wait(); // called if the buffer is full (try/catch removed for brevity)
}
buf.add(o);
notify(); // called in case there are any getters or putters waiting
}
public synchronized object get() {
// y: this is where c2 tries to acquire the lock (i.e. at the beginning of the method)
while (buf.size()==0) {
wait(); // called if the buffer is empty (try/catch removed for brevity)
// x: this is where c1 tries to re-acquire the lock (see below)
}
object o = buf.remove(0);
notify(); // called if there are any getters or putters waiting
return o;
}
所以除非你非常确定notify没有问题,大部分情况还是是用notifyall。
更多详细的介绍可以参看:
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
关于msyql事务隔离你要知道
什么是事务?事务是数据库管理系统执行过程中的一个逻辑单位,由一个有限的数据库操作序列构成。数据库事务通常包含了一个序列的对数据库的读/写操作。包含有以下两个目的...
[阅读全文]
-
-
使用java实现网络爬虫
接着上面一篇,这一篇目的就是在于网络爬虫的实现,对数据的获取,以便分析。----->爬虫实现原理网络爬虫基本技术处理网络爬虫是数据采集的一种方法,实际项目...
[阅读全文]
-
-
java调用回调机制详解
调用和回调机制在一个应用系统中, 无论使用何种语言开发, 必然存在模块之间的调用, 调用的方式分为几种:1.同步调用同步调用是最基本并且最简单的一种调用方式, ...
[阅读全文]
-
-
-
-
-
网友评论