有人可以告诉我为什么下面的代码不是线程安全的吗?我得到的输出是 0 或 45 或 90。共享资源计数器有一个同步方法,所以我一直期望 90 作为输出。我在这里错过了什么吗?请指教。请让我知道如何使此代码线程安全。
class Counter{
long count = 0;
public synchronized void add(long value){
this.count += value;
}
}
class CounterThread extends Thread{
protected Counter counter = null;
public CounterThread(Counter counter){
this.counter = counter;
}
public void run() {
for(int i=0; i<10; i++){
counter.add(i);
}
}
}
public class Example {
public static void main(String[] args){
Counter counter = new Counter();
Thread threadA = new CounterThread(counter);
Thread threadB = new CounterThread(counter);
threadA.start();
threadB.start();
System.out.println(counter.count);
}
}