简体   繁体   English

使用AtomicInteger进行多线程处理不起作用

[英]Multithreading with AtomicInteger not working

public class SynchroExample {

   public final AtomicInteger integer = new AtomicInteger(0);

   private ExecutorService service = Executors.newFixedThreadPool(100);

   public void syn() {
      for (int i = 0; i < 1000; i++) {
          service.submit(() -> {
              integer.incrementAndGet();
          });
       }
       service.shutdown();
       System.out.println(integer.get());
   }

   public static void main(String [] args) {
      SynchroExample ex = new SynchroExample();
       ex.syn();
    }
}

Can someone please explain why this code doesn't work? 有人可以解释为什么这段代码不起作用? I was under the impression that AtomicInteger is threadsafe. 我的印象是AtomicInteger是线程安全的。 And this code is not returning 1000. 而且这段代码没有返回1000。

AtomicInteger is thread safe, but you have called AtomicInteger#get before all tasks finished. AtomicInteger是线程安全的,但您在所有任务完成之前调用了AtomicInteger#get ExecutorService#shutdown is not waiting for tasks to finish. ExecutorService#shutdown不等待任务完成。

See ExecutorService#shutdown docs : 请参阅ExecutorService#shutdown docs

This method does not wait for previously submitted tasks to complete execution. 此方法不会等待先前提交的任务完成执行。 Use awaitTermination to do that. 使用awaitTermination来做到这一点。

Use 采用

service.awaitTermination(10, TimeUnit.SECONDS)

to wait for all tasks finished. 等待所有任务完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM