这个主要给 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 尼泽特!