【发布时间】:2012-06-25 10:09:54
【问题描述】:
这两段代码有什么区别?各有什么优缺点?
1)
public class Example {
private int value = 0;
public int getNextValue() {
synchronized (this) {
return value++;
}
}
}
2)
public class Example {
private final Object lock = new Object();
private int value = 0;
public int getNextValue() {
synchronized (lock) {
return value++;
}
}
}
【问题讨论】:
-
第二种方法几乎总是更好(AFAIK)——但为什么呢?
this(只是外部的“对象”)的可见性有什么负面影响? “坏代码”怎么会干扰同步目标? -
您知道
pubilc synchronized int getNextValue(){...}与public int getNextValue(){synchronized(this){...}}完全相同吗?
标签: java multithreading synchronization