Wait until boolean value changes it state(等到布尔值改变它的状态)
问题描述
我有一个线程等待布尔值改变如下:
I have a thread which wait for a boolean value to change like this:
while(!value)
{
Thread.sleep(1000)
}
// Do some work after change of the value
这不是我喜欢的方式,因为会消耗大量 CPU.
This is not my prefered way to do this, cause of massive CPU consumption.
有什么办法可以阻塞线程,直到布尔值改变它的状态?
Is there any way to block the Thread, until the boolean value changes it state?
推荐答案
这不是我喜欢的方式,因为会消耗大量 CPU.
This is not my prefered way to do this, cause of massive CPU consumption.
如果这实际上是您的工作代码,那么就保持这样.每秒检查一次布尔值会导致没有可测量的 CPU 负载.什么都没有.
If that is actually your working code, then just keep it like that. Checking a boolean once a second causes NO measurable CPU load. None whatsoever.
真正的问题是检查值的线程可能看不到由于缓存而在任意长时间内发生的更改.为保证值在线程间始终保持同步,需要在变量定义中放入 volatile 关键字,即
The real problem is that the thread that checks the value may not see a change that has happened for an arbitrarily long time due to caching. To ensure that the value is always synchronized between threads, you need to put the volatile keyword in the variable definition, i.e.
private volatile boolean value;
请注意,将访问放在 synchronized
块中,例如在使用其他答案中描述的基于通知的解决方案时,将具有相同的效果.
Note that putting the access in a synchronized
block, such as when using the notification-based solution described in other answers, will have the same effect.
这篇关于等到布尔值改变它的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:等到布尔值改变它的状态
基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01