本来我预期的结果应该是1000,可打印出来的总是990多
这里是源代码
- Java code
package ex29;import java.util.concurrent.*;public class Ex29_4 { private Integer sum = new Integer(0); public Ex29_4(){ ExecutorService executor = Executors.newFixedThreadPool(1000); for(int i = 0 ; i<1000 ; i++){ executor.execute(new sumTask()); } executor.shutdown(); while(!executor.isTerminated()){ } System.out.println("What is the sum? "+sum.intValue()); } public static void main(String[] args) { // TODO 自动生成方法存根 Ex29_4 ex = new Ex29_4(); } class sumTask implements Runnable{ public synchronized void run(){ int value = sum.intValue()+1; sum = value; } }}
------解决方案--------------------------------------------------------
你在run上面的同步是无效的,有与没有是一回事这里
你new了一千个sumTask,每次同步都在各自的对象上加锁
可以去掉run上的同步,同时将private Integer sum = new Integer(0);改为
private AtomicInteger sum = new AtomicInteger(0);
然后将run的方法体改成sum.getAndIncrement()
------解决方案--------------------------------------------------------
看到同步就想点进来看,结果发现已经没我啥事了。
另一个方案就是自己以sum为目标写同步块。
------解决方案--------------------------------------------------------
- Java code
public Ex29_4() { ExecutorService executor = Executors.newFixedThreadPool(1000); sumTask task = new sumTask(); for (int i = 0; i < 1000; i++) { executor.execute(task); } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println("What is the sum? " + sum.intValue()); }
------解决方案--------------------------------------------------------