Thread.sleep()的Java性能问题 [英] Java performance issue with Thread.sleep()

查看:678
本文介绍了Thread.sleep()的Java性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内联Java IDE提示声明,在循环中调用Thread.sleep会导致性能问题。我在文档的其他地方找不到任何解释。这句话。

Inline Java IDE hint states, "Invoking Thread.sleep in loop can cause performance problems." I can find no elucidation elsewhere in the docs re. this statement.

为什么?怎么样?还有什么其他方法可以延迟线程的执行?

Why? How? What other method might there be to delay execution of a thread?

推荐答案

这不是线程。在循环中睡眠本身是一个性能问题,但通常暗示你做错了。

It is not that Thread.sleep in a loop itself is a performance problem, but it is usually a hint that you are doing something wrong.

while(! goodToGoOnNow()) {
   Thread.sleep(1000);
}

使用 Thread.sleep 仅当您要暂停线程一段时间时。如果你想等待一定的条件,请不要使用它。

Use Thread.sleep only if you want to suspend your thread for a certain amount of time. Do not use it if you want to wait for a certain condition.

对于这种情况,你应该使用 wait / notify 或者并发utils包中的一些构造。

For this situation, you should use wait/notify instead or some of the constructs in the concurrency utils packages.

应该使用 Thread.sleep 进行轮询仅在等待当前JVM外部的条件时(例如,等待另一个进程写入文件)。

Polling with Thread.sleep should be used only when waiting for conditions external to the current JVM (for example waiting until another process has written a file).

这篇关于Thread.sleep()的Java性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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