为什么我的应用程序在某些时候返回错误的输出?

Wil*_*ood 1 java thread-safety

我有以下代码:

public class Test1 {

private static long value = 0;

public static void main(String[] args) {
    Thread1 k = new Thread1();
    Thread1 t = new Thread1();
    k.start();
    t.start();
    while (k.isAlive() & t.isAlive());
    System.out.println(value);
}

public static void addOne() {
    long temp = value;
    temp = temp + 1;
    value = temp;
}
}

class Thread1 extends Thread {

public void run() {
    for (int i=0; i<100; i++)
        Test1.addOne();
}
Run Code Online (Sandbox Code Playgroud)

}

通常当我运行它时,我得到200的输出,但很少有我得到100和151的输出.是什么原因造成的?

kih*_*eru 5

线程调度是不可预测的:

public static void addOne() {
    long temp = value;
    // Assume the thread is somewhere here when the system
    // puts it to sleep
    temp = temp + 1;
    // ...or here
    // ... Then the old value is used when it gets cpu time again
    value = temp;
}
Run Code Online (Sandbox Code Playgroud)

要修复,例如:

public static synchronized void addOne() ...
Run Code Online (Sandbox Code Playgroud)

防止线程踩在彼此的脚趾上.另一种方法是使用AtomicLong,并使用incrementAndGet().