【发布时间】: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 尼泽特!
【问题讨论】:
-
如果 JB 的回答帮助您解决了问题,您应该将其标记为已接受...
-
@Louis Wasserman 我会的,我还不能
标签: java multithreading