while 循环停止检查 if 语句?
While-loop stops checking if-statement?
我有一个 while 循环,例如:
boolean a = false;
MyClass b = new MyClass();
b.b = false;
// b is used in other thread...
while(!a){
if(b.b){
throw new Exception("b is true");
}
}
在这种情况下,a
永远不会变为真,但经过一些运行后,布尔变量 b.b
应该变为真。奇怪的是,while 循环从未离开过,我的程序陷入了无限循环。
我想知道为什么并决定在循环中添加一个 System.out.print
语句:
while(!a){
if(b.b){
throw new Exception("b is true");
}
System.out.println("there is something more to execute");
}
值得注意的是,我的代码运行正常。 while 循环遍历 if 语句,直到 b.b
为真并且抛出异常离开循环。
会不会是第一种情况程序停止检查if语句是因为编译器认为没有必要再检查了?如果不是,谁能给我解释一下,为什么第一种情况不行,而第二种情况可以?
如果你在多线程环境中工作,你需要将你的变量(以访问多个线程的为准)标记为volatile
,否则,不保证当前线程可以看到写入的结果通过另一个线程。
换句话说,一个线程写入(更改)变量 a
的值,而另一个线程不能保证看到它(因为线程可能 copy/cache 变量),这是导致你的 while
循环不中断。
我建议您查看 here 并了解 volatile
如何在多线程环境中工作。下面的文字(强调我的)来自同一个 link:
Changes to a volatile
variable are always visible to other threads. When a thread reads a volatile
variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.
我有一个 while 循环,例如:
boolean a = false;
MyClass b = new MyClass();
b.b = false;
// b is used in other thread...
while(!a){
if(b.b){
throw new Exception("b is true");
}
}
在这种情况下,a
永远不会变为真,但经过一些运行后,布尔变量 b.b
应该变为真。奇怪的是,while 循环从未离开过,我的程序陷入了无限循环。
我想知道为什么并决定在循环中添加一个 System.out.print
语句:
while(!a){
if(b.b){
throw new Exception("b is true");
}
System.out.println("there is something more to execute");
}
值得注意的是,我的代码运行正常。 while 循环遍历 if 语句,直到 b.b
为真并且抛出异常离开循环。
会不会是第一种情况程序停止检查if语句是因为编译器认为没有必要再检查了?如果不是,谁能给我解释一下,为什么第一种情况不行,而第二种情况可以?
如果你在多线程环境中工作,你需要将你的变量(以访问多个线程的为准)标记为volatile
,否则,不保证当前线程可以看到写入的结果通过另一个线程。
换句话说,一个线程写入(更改)变量 a
的值,而另一个线程不能保证看到它(因为线程可能 copy/cache 变量),这是导致你的 while
循环不中断。
我建议您查看 here 并了解 volatile
如何在多线程环境中工作。下面的文字(强调我的)来自同一个 link:
Changes to a
volatile
variable are always visible to other threads. When a thread reads avolatile
variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.