我有一个问题。为什么此代码(带有1个“ while”程序)运行死循环,而2个“ while”程序却没有死循环?
public class VolatileTest2 {
private volatile static boolean isOver = false;
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
int a=0;
while (!isOver){//1
a=5;
} ;
/* while (true){ //2
a=5;
if(!isOver)break;
} ;*/
System.out.println(a);
}
});
thread.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
isOver = true;
}
}
答案 0 :(得分:1)
这不是不确定的。只是执行得太快。如果您在代码中添加一些输出并在内部添加一些睡眠,您将了解发生了什么。
public class VolitileTest {
private volatile static boolean isOver = false;
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
int a=0;
System.out.println("IsOver before while =" + isOver);
while (!isOver){//1
System.out.println("IsOver in =" + isOver);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
a=5;
} ;
/* while (true){ //2
a=5;
System.out.println("IsOver in =" + isOver);
if(!isOver) {
break;
}
}*/
System.out.println("Out of while: " + a);
}
});
thread.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("IsOver before set true =" + isOver);
isOver = true;
System.out.println("IsOver after set true =" + isOver);
}
输出:
IsOver before while =false
IsOver in =false
IsOver in =false
IsOver in =false
IsOver before set true =false
IsOver after set true =true
Out of while: 5