我在一个紧密的循环中有两个未同步的线程,将全局变量X递增(x = 100000)。
正确的全局最终值应为2 * X,但是由于它们不同步,因此会更少,根据经验,它通常仅比X小一点
但是,在所有测试运行中,global的值永远不会低于X。
最终结果是否有可能小于x(小于100000)?
public class TestClass {
static int global;
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread( () -> { for(int i=0; i < 100000; ++i) { TestClass.global++; } });
Thread t2 = new Thread( () -> { for(int i=0; i < 100000; ++i) { TestClass.global++; } });
t.start(); t2.start();
t.join(); t2.join();
System.out.println("global = " + global);
}
}