基于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。
更多详细的介绍可以参看:
http://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again
相关文章
Java数据结构及算法实例:考拉兹猜想 Collatz Conjecture
这篇文章主要介绍了Java数据结构及算法实例:考拉兹猜想 Collatz Conjecture,本文直接给出实现代码,代码中包含详细注释,需要的朋友可以参考下2015-06-06
Mybatis中动态SQL,if,where,foreach的使用教程详解
MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑。这篇文章主要介绍了Mybatis中动态SQL,if,where,foreach的使用教程,需要的朋友可以参考下2017-11-11
java 查询oracle数据库所有表DatabaseMetaData的用法(详解)
下面小编就为大家带来一篇java 查询oracle数据库所有表DatabaseMetaData的用法(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2016-11-11
SpringBoot @Scheduled Cron表达式使用方式
这篇文章主要介绍了SpringBoot @Scheduled Cron表达式使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2025-03-03


最新评论