Is it okay to use Thread.sleep() in a loop in Java

2019-06-15 15:58发布

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?

2条回答
smile是对你的礼貌
2楼-- · 2019-06-15 16:19

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.

查看更多
Explosion°爆炸
3楼-- · 2019-06-15 16:44

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

查看更多
登录 后发表回答