【发布时间】:2019-12-16 16:30:42
【问题描述】:
我在一个紧密循环中有两个不同步的线程,将全局变量递增 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);
}
}
【问题讨论】:
标签: java multithreading synchronization race-condition data-race