可以在Java循环中使用Thread.sleep()定期执行某些操作吗? [英] Is it okay to use Thread.sleep() in a loop in Java, to do something at regular intervals?

查看:8617
本文介绍了可以在Java循环中使用Thread.sleep()定期执行某些操作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过一些线程,它们说在循环中调用Thread.sleep()是有问题的,并且是严重的性能问题.但是在某些情况下,这似乎是最自然的事情.

I have read some threads that said that calling Thread.sleep() in a loop is problematic and is a serious performance issue. But in some cases it seems the most natural thing to do.

例如,如果我希望我的应用程序每 3分钟执行一次操作(让我们说这是自动保存)

For example if I want my application to do something every 3 minutes (lets say it's an autosave)

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?

推荐答案

长时间睡眠不会影响性能.如果您睡了5毫秒,请检查一下状况,然后再入睡5毫秒,等等,持续3分钟.这会降低性能.

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.

如果您需要每3分钟执行一次操作,则改用调度程序会更有意义.

If what you need is to do something every 3 minutes, it would make more sense to use a scheduler instead.

您可以查看 javadoc非常类似的示例,参见ScheduledExecutorService .

这篇关于可以在Java循环中使用Thread.sleep()定期执行某些操作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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