关于 Java 同步,我尝试了一个示例(来自 TLF-SOFT-VTC.java.6CFE),但结果是错误的,为什么它不同步?编码 :
public class InterferenceFix extends Thread {
String name;
static boolean isZero = true;
static int counter = 0;
public static void main(String arg[]) {
InterferenceFix one = new InterferenceFix("one");
InterferenceFix two = new InterferenceFix("two");
one.start();
two.start();
}
InterferenceFix(String nameString) {
name = nameString;
}
public void run() {
for (int i = 0; i < 100000; i++) {
update();
}
System.out.println(name + ": " + counter);
}
synchronized void update() {
if (isZero) {
isZero = false;
counter++;
} else {
isZero = true;
counter--;
}
}
}