Is it okay to use Thread.sleep() in a loop in Java, to do something at regular intervals?

半城伤御伤魂 提交于 2019-12-12 10:30:54

问题


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.

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?


回答1:


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.

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

You can have a look at the javadoc of ScheduledExecutorService for a very similar example.




回答2:


You should better use ScheduledExecutorService if you want to put delay. 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



来源:https://stackoverflow.com/questions/14561324/is-it-okay-to-use-thread-sleep-in-a-loop-in-java-to-do-something-at-regular-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!