1

这个主要给 ExecutorService 1000 个可运行对象(测试人员),他们所做的只是睡眠 10 毫秒,然后将 1 添加到静态计数器,主要是假设要等到所有执行完成,但计数器会上升到 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 尼泽特!

4

1 回答 1

6

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

改用 an AtomicLong,然后调用incrementAndGet()this AtomicLong

于 2012-07-26T09:39:18.423 回答