内存一致性错误和线程干扰之间有什么区别?如何使用同步来避免它们的不同?请举例说明.我无法从sun Java教程中得到这个.任何阅读材料的建议,只是在java的上下文中理解这将是有帮助的.
/*
This should always produce 0 as output since all three methods increment(), decrement(), value() are thread safe(synchronized). but it is returning 1
*/
class Counter implements Runnable {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
public void run() {
try {
this.increment();
Thread.sleep(1000);
this.decrement();
Thread.sleep(1000);
this.increment();
Thread.sleep(1000);
this.decrement();
Thread.sleep(1000);
}
catch (InterruptedException e){
return;
}
}
public static void …Run Code Online (Sandbox Code Playgroud)