关于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--;
}
}
}
Run Code Online (Sandbox Code Playgroud)
只有你的update方法是同步的,这意味着环可以在两个线程同时运行,只有update自己不可以.
而且-在synchronized关键字实际锁定的对象this,并在你的情况,我们在谈论2不同的情况下,这意味着他们锁定不同this.这意味着积极-线程不与对方的工作,任何方式干扰,他们既可以同时运行.
如果这确实是你想要的,你可能最好创建一个静态锁:
private static final Object lock = new lock();
Run Code Online (Sandbox Code Playgroud)
并改变update(或运行)到这个:
void update() {
synchronized (lock) {
if (isZero) {
isZero = false;
counter++;
} else {
isZero = true;
counter--;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你需要同步for循环,只需在循环周围以相同的方式使用锁而不是内部update.