以下代码同步块与在Java中
public class Coordination {
private volatile int counter = 0;
public static void main(String ... args) throws Exception {
new Coordination().volatileWithCoordination();
}
public synchronized void inc() {
counter++;
}
public void volatileWithCoordination() throws Exception {
Thread th1 = new Thread(new Runnable() {
@Override
public void run() {
for(int k = 0; k < 10_000_000; k++) {
synchronized(this) {
//inc();
counter++;
}
}
}});
Thread th2 = new Thread(new Runnable() {
@Override
public void run() {
for(int k = 0; k < 10_000_000; k++) {
//synchronized(this) {
inc();
//counter++;
//}
}
}});
th1.start();
th2.start();
th1.join();
th2.join();
System.out.println("counter: "+counter);
}
}
的
counter: 18025867
展品不正确的,非确定性的结果而切换到同步方法限定符:在可运行的第一个线程的
inc();
//counter++;
( th1
)给出的预期输出:
counter: 20000000
什么造成这种lost update
行为,为什么在这种情况下同步方法的行为与同步(this)块不同?
预先感谢您。
块在两个独立线程实例上同步,但该方法在同一个坐标实例上同步。 –