我正在玩线程,我不明白为什么这不像我想的那样工作。
我正在尝试使用线程计算总和,并期望线程池在我打印出结果时等待所有任务完成(由于 shutdown() 调用和 isTerminated() 检查)。
我在这里想念什么?
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test5 {
private Integer sum= new Integer(0);
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
Test5 obj = new Test5();
for(int i=0; i<1000; i++){
pool.execute(obj.new Adding());
}
pool.shutdown();
while(!pool.isTerminated()) {
//could be empty loop...
System.out.println(" Is it done? : " + pool.isTerminated());
}
System.out.println(" Is it done? : " + pool.isTerminated());
System.out.println("Sum is " + obj.sum);
}
class Adding implements Runnable {
public void run() {
synchronized(this) {
int tmp = sum;
tmp+=1;
sum=new Integer(tmp);
}
}
}
}
虽然我确实得到了很好的结果,但我也得到了这样的输出:
Is it done? : true
Sum is 983