在Java中,为什么在下面的代码中synchronized
可以注释掉?因为加法几乎是原子的,因此错误或失败的概率太小?
public class AddInParallel {
public static void main(String[] args) {
class sumValue {
public int sum = 0;
sumValue() {}
public /*synchronized*/ void add(int i) {
sum += i;
}
}
// final makes sumValue visible to threads
final sumValue sum = new sumValue();
class Adder implements Runnable {
// used to distinguish threads
private int id;
Adder(int index) { id = index; }
public void run() { sum.add(1); }
}
// start threads
Thread[] threads = new Thread[1000];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Adder(i) {});
threads[i].start();
}
// wait for threads above to finish
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(sum.sum);
}
}