我在winterbe.com上遇到了以下示例,该示例演示了原子变量的使用。
// From http://winterbe.com/posts/2015/05/22/java8-concurrency-tutorial-atomic-concurrent-map-examples/
public class Test_AtomicInteger {
public static void main(String[] args) {
AtomicInteger atomicInt = new AtomicInteger(0);
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, 1000)
.forEach(i -> {
Runnable task = () ->
atomicInt.updateAndGet(n -> n + 2);
executor.submit(task);
});
executor.shutdownNow();
System.out.println(atomicInt.get()); // => 2000
}
}
了解如何从线程安全方案中推导出期望值2000。但是,当我尝试在eclipse IDE上执行它时,每次运行时它都会给出不同的输出值。想看看是否有人知道为什么会这样。非常感谢。
基本上,Threadmain
是shutdownNow
在所有执行的任务完成之前调用(即使不调用shutdownNow
也不会看到2000
,因为您AtomicInteger
在执行程序执行之前仍在查询)。
您真的想阻塞,直到执行程序完成或发生超时:
executor.shutdown();
executor.awaitTermination(100, TimeUnit.MILLISECONDS);
如果您仔细查看过这篇文章的作者,则该文章的定义为:
public static void stop(ExecutorService executor) {
try {
executor.shutdown();
executor.awaitTermination(60, TimeUnit.SECONDS);
}
....
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句