동기화 간단한 멀티 스레딩 시험 사용. 나는 그것이 "동기화"되었다면 다른 스레드가 기다릴 것이라고 생각했다. 내가 뭘 놓치고 있니? 이 같은자바는 스레드로부터 안전하지 멀티 스레딩 동기화
0: 0 2: 0 1: 0 3: 3
및 기타 변화 :
0: 1 2: 0 1: 2 3: 3
그러나 실제 출력 :
public class MultithreadingCounter implements Runnable {
static int count = 0;
public static void main(String[] args) {
int numThreads = 4;
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++)
threads[i] = new Thread(new MultithreadingCounter(), i + "");
for (int i = 0; i < numThreads; i++)
threads[i].start();
for (int i = 0; i < numThreads; i++)
try {
threads[i].join();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
increment();
}
public synchronized void increment(){
System.out.print(Thread.currentThread().getName() + ": " + count + "\t");
count++; // if I put this first or increment it directly in the print line, it works fine.
}
}
나는이 같은 것을 표시 거라 생각 했어요. 그것은
아. 나는 매일 새로운 것을 배운다. 감사. – user1877411
충분히 게이트를 ('synchronized'와 조합하여)이를 'static'을 싶은, 또는 그뿐만 아니라 변수'volatile' 할 것인가? –
(올바른) 동기화로 충분합니다. 그것은 이미 증분이 후속 읽기들과의 '이전 - 관계'를 가지고 있다는 것을 보장한다. 그것은 모두 '휘발성 (volatile)'이 추가하는 것이다. –