스레드를 사용하는 작은 프로그램이 실제로 나를 괴롭 히고 있습니다. 왜 이것이 출력을 제공하지 않는지 설명 할 수 있습니까?스레드가 올바른 출력을 제공하지 않음
class FirstClass {
public static void main(String args[]) {
Class2 two = new Class2();
Thread thread1 = new Thread(two);
thread1.start();
Class3 three =new Class3(two);
Thread thread2 = new Thread(three);
thread2.start();
}
}
class Class2 implements Runnable {
public Boolean variable1 = false;
@Override
public void run() {
System.out.println("Sleeping thread");
try {
Thread.sleep(3000);
}catch(Exception e){}
variable1=true;
System.out.println("Variable 1 = " + variable1);
}
}
class Class3 implements Runnable {
Class2 two;
public Class3(Class2 _two) {
this.two = _two;
}
@Override
public void run() {
while(!this.two.variable1) {
//System.out.println("in while");
}
System.out.println("Variable1 was changed to true");
}
}
위, 날 '스레드 자'는 정확한 출력 '는 변수 1 = TRUE', '해당 변수 1로 변경 한'을 제공한다. 이제 프로그램을 약간 변경하고 'System.out.println ("in"while "); 나는 "Variable1이 true로 변경되었다"는 것을 얻지 못한다. while 루프에서 벗어나지 않은 것처럼 보이지만, 왜 System.out.println ("while") '이 튀어 나오는가? 없는 사람이 내가 가장 감사하게 될 것입니다 무슨 일이 일어나고 있는지 설명 할 수 있다면
감사
변수 휘발성을 – radai
으로 만들려고 시도하십시오 [루프는 인쇄 문없이 변경된 값을 보지 못합니다] (http://stackoverflow.com/questions/25425130/loop-doesnt-see-changed-value-without- a-print-statement) – Boann