import java.util.concurrent.ExecutorService;
import static java.util.concurrent.Executors.newFixedThreadPool;
public class Test {
private static volatile int i = 0; //加 volatile 没用,它并不能保证原子性
private static synchronized void increase() {
//此处加上 Synchronized 可以解决问题,成功返回20000
//这里加了 Synchronized 后就前面的 i 位置就不需要加 volatile 了
i++;
}
public static void main(String[] args) throws InterruptedException {
ExecutorService e = newFixedThreadPool(2);
Runnable r = () -> {
for (int j = 0; j < 10000; j++) {
increase();
}
};
e.execute(r);
e.execute(r);
Thread.sleep(1000);
e.shutdown();
System.out.println(i);
}
}
来源:CSDN
作者:喵了个咪的回忆丶
链接:https://blog.csdn.net/dl674756321/article/details/103543500