시드 :
나는 자바 휘발성 개념을 이해하는 코드를 다음과 쓴하지만 출력은 혼란보다는 개념을 명확히 할 것으로 보인다. 수정, 명확화 및 피드백 환영 이해된다.
package threading;
public class UnSyncRead {
//volatile static int value = 987;
static int value = 987;
public static void main(String[] args) {
ThreadEx4 t = new ThreadEx4(value);
t.start();
for(int i=0;i<4;i++) {
Thread thread = new Thread( new ThreadEx3(value));
thread.start();
}
}
}
class ThreadEx3 implements Runnable{
private int i;
public ThreadEx3(int i) {
this.i=i;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getId()+ " "+Thread.currentThread().getName()+" "+ " inside "+i);
}
}
class ThreadEx4 extends Thread{
private int i;
public ThreadEx4(int i) {
this.i=i;
}
public void run() {
++i;
System.out.println("changed the value to "+i);
}
}
이 프로그램은 다음과 같은 출력을 제공합니다
changed the value to 988
12 Thread-1 inside 987
13 Thread-2 inside 987
14 Thread-3 inside 987
15 Thread-4 inside 987
하지만 메이크업의에 코드를 수정할 경우 value
변수를 volatile
다음과 같이 변경을 수행하고 코드를 실행하여.
public class UnSyncRead {
volatile static int value = 987;
//static int value = 987;
public static void main(String[] args) {
ThreadEx4 t = new ThreadEx4(value);
t.start();
for(int i=0;i<4;i++) {
Thread thread = new Thread( new ThreadEx3(value));
thread.start();
}
}
}
나는 휘발성 키워드없이 실행했을 때 정확히 동일한 출력을 다음 얻을.
changed the value to 988
12 Thread-1 inside 987
13 Thread-2 inside 987
14 Thread-3 inside 987
15 Thread-4 inside 987
for 루프에서 스레드가 여전히 값 읽기 왜 내 질문은 value
같은 변수를 987
하지 988
심지어 휘발성 키워드를 구현 한 후,.
깊이이 문제에 대한 답을 주셔서 감사합니다.
틸로 :
이것은 모두에서 멀티 스레딩 함께 할 수 없다, 그것은 훨씬 더 근본적인 문제입니다.
class ThreadEx4 extends Thread{
private int i;
public ThreadEx4(int i) {
this.i=i;
}
public void run() {
++i;
System.out.println("changed the value to "+i);
}
}
당신은 당신의 개인 변수를 변경 i
하지 글로벌, 여기에 static
필드.
자바는 값으로 주위에 물건을 전달합니다. 당신이 말할 때 그래서 new ThreadEx4(myInteger)
, 생성자의 수의 내부를 받게됩니다 myInteger
. 그것의 로컬 복사본 않는 무엇이든간에 영향을주지 않습니다 myInteger
전혀.
멀티 스레딩 실험을 계속하려면, 로컬 변수를 제거하고 할 얻을
class Ex4 extends Runnable {
@Override
public void run(){
int newValue = ++UnSyncRead.value;
System.out.println("changed the value to "+newValue);
}
}
// and the same for the other runnables