【问题标题】:ExecutorService not doing its job?ExecutorService 没有做好它的工作?
【发布时间】:2012-07-26 09:34:53
【问题描述】:

这个 main 给 ExecutorService 1000 个可运行对象(测试人员),他们所做的只是睡眠 10 毫秒,然后将 1 添加到静态计数器,假设 main 等到所有执行都完成,但计数器会上升大约 970 次处决……为什么?

public class Testit {
    public static void main (String arg[]) {
        int n=1000;
        ExecutorService e1 =  Executors.newFixedThreadPool(20);
        for (int i=0 ;i <n ;i++) {
            e1.execute(new Tester());
        }
        e1.shutdown();
        try {
            e1.awaitTermination(1, TimeUnit.DAYS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Executed "+Tester.tester()+" Tasks.");
    }
}

和测试人员类:

public class Tester implements Runnable {
    public static long tester=0;
    @Override
    public void run() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally { tester++; }
    }
    public static long tester() {
        long temp=tester;
        tester=0;
        return temp;
    }
}

编辑

问题解决者:

finally { synchronized (lock) {tester++;} } 

感谢 JB 尼泽特!

【问题讨论】:

标签: java multithreading


【解决方案1】:

因为您不同步对计数器的访问,并且由于写入 long 不是原子的,++ 也不是,两个并发线程递增计数器可能会导致完全不一致的结果,或者只一个增量而不是 2。

请改用AtomicLong,并在此AtomicLong 上调用incrementAndGet()

【讨论】:

猜你喜欢
  • 2018-10-06
  • 2020-11-23
  • 1970-01-01
  • 2020-02-08
  • 2013-10-10
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多