以下代码让我感到困惑,因为同步关键字不会阻止两个线程同时访问SafeThread.value。
当我运行代码时,结果不是预期的20000。
我还尝试使increment()非静态,并让两个线程具有相同的SafeThread实例。它也没用。我错过了什么吗?
public class MultithreadTesting extends Thread {
public static void main(String[] args) {
MultithreadTesting thread1 = new MultithreadTesting();
MultithreadTesting thread2 = new MultithreadTesting();
thread1.start();
thread2.start();
System.out.println(SafeThread.value);
}
public void run() {
int i = 10000;
while (i > 0) {
SafeThread.increment();
i--;
}
}
}
public class SafeThread {
public static int value = 0;
public synchronized static void increment() {
value++;
}
}