6 回答

TA贡献1815条经验 获得超10个赞
1、用了synchronized修饰了方法,又用synchronized修饰方法体,这两者是等效的,都是获得this(MyStack)的对象监视器并且临界区也是一致的,同是因为synchronized是可重入的,所以你这样用不会发生错误,但是这是不必要的;
2、可能会发生 @房管局规划部 中出现的错误,wait()可能出现假唤醒,而不满足临界条件,后续逻辑就会异常。
可以参看jdk wait()方法的注释描述:
所以,应该是这样:
synchronized( method_or_shared_object){
while(list.size()<=0)
wait();
// pop something...
}
一般来说,都需要在while(condition) wait()来防止假唤醒。

TA贡献1811条经验 获得超6个赞

TA贡献1784条经验 获得超9个赞
首先synchronized修饰方法的问题
对于非static方法,其作用相当于synchronized(this):
synchronized void method(){
// method body
}
// 等价于
void method() {
synchronized(this){
// method body
}
}
对于static方法,其相当于synchronized(YourClass.class):
class YourClass {
synchronized static void method() {
// method body
}
// 等价于
static void method() {
synchronized(YourClass.class) {
// method body
}
}
}
其次关于假唤醒问题,就是@spance说的。官方docde描述是:
A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup.
官方给出的解决方案是:
synchronized (obj) {
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
}
添加回答
举报