在Java中检查另一个线程布尔值对性能而言哪个更好 [英] Which one is better for performance to check another threads boolean in java

查看:63
本文介绍了在Java中检查另一个线程布尔值对性能而言哪个更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

while(!anotherThread.isDone());

while(!anotherThread.isDone())
    Thread.sleep(5);

推荐答案

正如其他人所说,在这种情况下最好只使用join.但是,我想概括一下您的问题,并提出以下要求:

As others have said, it's better to just use join in this case. However, I'd like to generalize your question and ask the following:

通常,当线程正在等待依赖于另一个线程的事件时,最好这样做:

  1. 使用阻止机制(例如,join,条件变量等)或
  2. 忙转不睡或
  3. 忙碌的睡眠吗?
  1. Use a blocking mechanism (i.e. join, conditional variable, etc.) or
  2. Busy spin without sleep or
  3. Busy spin with sleep?

现在让我们看看每种情况的含义:

Now let's see what are the implications for each case:

  1. 在这种情况下,使用阻塞调用将有效地将线程从CPU上移开,并且直到发生预期事件时才重新安排线程.有利于资源利用(线程会浪费CPU周期),但是如果事件可能发生得非常频繁且间隔很小(例如,上下文切换比发生事件所花费的时间要多得多),则效率不高).一般情况下,事件最终会发生的时候很好,但是您不知道要多久.
  2. 在第二种情况下,您正在忙于旋转,这意味着您在不执行有用工作的情况下正在积极使用CPU.这与情况1相反:当预计事件很快发生时很有用,否则可能会不必要地占用CPU.
  3. 这种情况是一种权衡.您正在忙于旋转,但同时通过放弃CPU来允许其他线程运行.当您不希望使CPU饱和时,通常会使用此方法,但是预计该事件会很快发生,并且您希望确保在几乎实时时仍会在那里捕获该事件.它会发生.
  1. In this case, using a blocking call will effectively take your thread off the CPU and not schedule it again until the expected event occurs. Good for resource utilization (the thread would waste CPU cycles otherwise), but not very efficient if the event may occur very frequently and at small intervals (i.e. a context switch is much more time-consuming than the time it takes for the event to occur). Generally good when the event will occur eventually, but you don't know how soon.
  2. In case two, you are busy spinning, meaning that you are actively using the CPU without performing useful work. This is the opposite of case 1: it is useful when the event is expected to occur very very soon, but otherwise may occupy the CPU unnecessarily.
  3. This case is a sort of trade-off. You are busy spinning, but at the same time allowing other threads to run by giving up the CPU. This is generally employed when you don't want to saturate the CPU, but the event is expected to occur soon and you want to be sure that you will still be there in almost real time to catch it when it occurs.

这篇关于在Java中检查另一个线程布尔值对性能而言哪个更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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