아래 코드가 threadsafe가 아닌 이유를 알려주십시오. 내가 얻는 출력은 0 또는 45 또는 90입니다. 공유 리소스 카운터에는 동기화 된 메서드가 있으므로 출력으로 항상 90을 기다리고 있습니다. 내가 여기서 뭔가를 놓치고 있니? 제발 조언. 친절하게도이 코드를 threadsafe로 만드는 방법을 알려주십시오.동기화 된 메서드가 스레드 안전하지 않음
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);
}
}
만약 내가 올바른 값을 읽을 수도 동기화되어야합니다 –
왜? 당신은 간단한 긴 가치를 읽습니다. 그건 원자가가 될까요? – JohnB
공개 여부 http://jeremymanson.blogspot.nl/2007/08/atomicity-visibility-and-ordering.html에 대해 알아보십시오. 어쩌면 내가 틀렸어 –