为什么这个 'if' 语句 运行 不会在 while 循环中没有其他事情发生在 while 循环中?
Why won't this 'if' statement run in a while loop without something else also happening in the while loop?
我遇到一个问题,如果 while 循环中在它之前发生了其他事情,if 语句只是 运行ning。
这是我要使用的代码:
public void load() throws IOException, InterruptedException {
while (true) {
if (findGame == true) {
System.out.println(findGame);
}
}
}
这是简化的,但它显示了我的问题。基本上,当findGame == true
时,if语句不会运行。我认为 if 语句不是 运行ning 的原因是变量没有被打印到控制台。
我做了一些测试,发现 if 语句 运行 具有以下代码:
public void load() throws IOException, InterruptedException {
while (true) {
System.out.println("foo"); // New code added
if (findGame == true) {
System.out.println(findGame);
}
}
}
我的问题是为什么它适用于上面的代码而不适用于第一个代码?两者之间的唯一区别是有效的那个在 while 循环中添加了其他东西。
如果有所不同,我上面显示的代码是 运行在单独的线程中。
If it makes a difference, the code I've shown above is running in a separate thread.
这就是问题所在。您依赖于一个线程设置的值在另一个线程中可见 - 如果不涉及内存障碍,就没有这样的保证。在您的第二个代码中,对 println
的调用几乎肯定负责创建读取线程所需的内存屏障 "see" 写入线程写入的值。不幸的是,内存模型很难:(
如果你使用AtomicBoolean
instead of just a boolean
field, you may well find the first code works instead - but even so, a tight loop is generally a bad idea. It would be better to use a semaphore or some similar kind of signalling, so the "reading" thread could just wait (idly) until there's a change. Look into java.util.concurrent
for classes such as Semaphore
and CountDownLatch
。 (你可以只使用 wait
和 notify
,但如果你使用更高级别的抽象,它会更简单。)
我遇到一个问题,如果 while 循环中在它之前发生了其他事情,if 语句只是 运行ning。
这是我要使用的代码:
public void load() throws IOException, InterruptedException {
while (true) {
if (findGame == true) {
System.out.println(findGame);
}
}
}
这是简化的,但它显示了我的问题。基本上,当findGame == true
时,if语句不会运行。我认为 if 语句不是 运行ning 的原因是变量没有被打印到控制台。
我做了一些测试,发现 if 语句 运行 具有以下代码:
public void load() throws IOException, InterruptedException {
while (true) {
System.out.println("foo"); // New code added
if (findGame == true) {
System.out.println(findGame);
}
}
}
我的问题是为什么它适用于上面的代码而不适用于第一个代码?两者之间的唯一区别是有效的那个在 while 循环中添加了其他东西。
如果有所不同,我上面显示的代码是 运行在单独的线程中。
If it makes a difference, the code I've shown above is running in a separate thread.
这就是问题所在。您依赖于一个线程设置的值在另一个线程中可见 - 如果不涉及内存障碍,就没有这样的保证。在您的第二个代码中,对 println
的调用几乎肯定负责创建读取线程所需的内存屏障 "see" 写入线程写入的值。不幸的是,内存模型很难:(
如果你使用AtomicBoolean
instead of just a boolean
field, you may well find the first code works instead - but even so, a tight loop is generally a bad idea. It would be better to use a semaphore or some similar kind of signalling, so the "reading" thread could just wait (idly) until there's a change. Look into java.util.concurrent
for classes such as Semaphore
and CountDownLatch
。 (你可以只使用 wait
和 notify
,但如果你使用更高级别的抽象,它会更简单。)