[英]ExecutorService not doing its job?
This main giving an ExecutorService 1000 runnables (Testers) that all they do is sleep 10 millis and then add 1 to a static counter, the main was suppose to wait untill ALL executions are FINISHED, but yet the counter gets up to something around the 970 executions... why? 这个主函数给ExecutorService 1000个可运行对象(测试器)提供了所有睡眠,然后睡眠1毫秒,然后将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.");
}
}
and Tester Class: 和测试人员类别:
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;
}
}
EDIT 编辑
problem solved by: 解决的问题:
finally { synchronized (lock) {tester++;} }
Thanks JB Nizet! 感谢JB Nizet!
Because you don't synchronize the access to the counter, and since writing a long is not atomic, and ++
isn't either, two concurrent threads incrmenting the counter could lead to a completely inconsistent results, or to only one increment instead of 2. 因为您不同步对计数器的访问,并且由于写long不是原子的,并且
++
也不是原子,所以两个并发增加计数器的并发线程可能导致结果完全不一致,或者仅导致一个增量而不是2。
Use an AtomicLong
instead, and call incrementAndGet()
on this AtomicLong
. 请改用
AtomicLong
,然后在此AtomicLong
上调用AtomicLong
incrementAndGet()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.