简体   繁体   English

使用ExecutorService进行并发

[英]concurrency using ExecutorService

I have this simple program to count numbers from 1 to 9 using ThreadPool and ExecutorService. 我有这个简单的程序,使用ThreadPool和ExecutorService计算从1到9的数字。 Each Thread is waiting for 1 sec to execute. 每个线程等待1秒执行。 However, below program gives me random output for each execution. 但是,下面的程序为每次执行提供了随机输出。

How do I fix this so that it always produces 45? 我如何解决这个问题,以便它总能产生45?

public static void main(String[] args) throws InterruptedException {
    AtomicLong count = new AtomicLong(0);
    ExecutorService executor = Executors.newFixedThreadPool(10);
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
    for(Integer i : list) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count.set(count.get() + i);
            }
        });
    }

    System.out.println("Waiting...");

    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
    System.out.println("Total::"+count.get());

    System.out.println("Done");
}

Instead of 代替

count.set(count.get() + i);

use 采用

count.addAndGet(i);

Method addAndGet adds value atomically but sequential get and set is not atomic operation. 方法addAndGet以原子方式添加值,但顺序getset不是原子操作。

AtomicLong has special methods which are atomic. AtomicLong有一些原子的特殊方法。 You only get atomic guarantees when using them (separate calls to add() and get() will not be atomic). 使用它们时只获得原子保证(对add()get()单独调用不是原子的)。 There are methods on AtomicLong which will "add" to the current value in an atomic fashion. AtomicLong上有一些方法可以以原子方式“添加”到当前值。

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

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