[英]Is it okay to use Thread.sleep() in a loop in Java, to do something at regular intervals?
I have read some threads that said that calling Thread.sleep() in a loop is problematic and is a serious performance issue. 我已经阅读了一些线程,说在循环中调用Thread.sleep()是有问题的,并且是一个严重的性能问题。 But in some cases it seems the most natural thing to do.
但在某些情况下,这似乎是最自然的事情。
For example if I want my application to do something every 3 minutes (lets say it's an autosave ) 例如,如果我希望我的应用程序每3分钟执行一次(假设它是自动保存 )
public void startAutosaveLoop(){
stop = false;
new Thread(new Runnable() {
@Override
public void run() {
while (!stop){
Thread.sleep(T*1000);
if (!stop){
// do something
}
}
}
}).start();
}
Is there a better way to doing this? 有没有更好的方法来做到这一点? Is this kind of situation problematic?
这种情况有问题吗?
If you sleep for a long time it won't affect the performance. 如果你长时间睡觉,它不会影响性能。 If you sleep for 5ms, check some condition, go back to sleep for 5 ms etc. for 3 minutes it will have some performance cost.
如果你睡了5ms,检查一些情况,回到睡眠5毫秒等3分钟,它将有一些性能成本。
If what you need is to do something every 3 minutes, it would make more sense to use a scheduler instead. 如果您需要的是每3分钟做一次,那么使用调度程序会更有意义。
You can have a look at the javadoc of ScheduledExecutorService for a very similar example. 您可以查看ScheduledExecutorService的javadoc以获取非常相似的示例。
You should better use ScheduledExecutorService if you want to put delay. 如果要延迟,最好使用ScheduledExecutorService 。 This interface supports future and/or periodic execution of task.
此接口支持将来和/或定期执行任务。
Pls check API doc for sample code and details: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html 请检查API文档以获取示例代码和详细信息: http : //docs.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.