等到布尔值更改它的状态 [英] Wait until boolean value changes it state

查看:168
本文介绍了等到布尔值更改它的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程这等待一个布尔值来改变这样的:

 而(!值)
{
  视频下载(1000)
}
//执行价值变动后的一些工作

这是不是我的$ P $要做到这一点pfered方式,大量消耗CPU的原因。

有什么办法来阻止线程,直到布尔值改变其状态?


解决方案

  

这是不是我的$ P $要做到这一点pfered方式,大量消耗CPU的原因。


如果它实际上是你的工作code,那么就保持这样。检查一个布尔值每秒一次的原因没有可衡量的CPU负载。无任何责任。

真正的问题是,检查值的线程可能不会看到已经发生了一个任意长的时间,由于缓存的变化。为确保该值线程之间总是同步的,你需要把volatile关键字的变量定义,即

 私人挥发性布尔值;

注意,将在同步块的访问,如用在其他的答案中描述的基于通知的解决方案时一样,也会有同样的效果。

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

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?

解决方案

This is not my prefered way to do this, cause of massive CPU consumption.

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.

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;

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.

这篇关于等到布尔值更改它的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆