如何在 Java 中正确使用 thread.sleep()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29115634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:42:37  来源:igfitidea点击:

How to use thread.sleep() properly in Java?

java

提问by smwikipedia

I see a lot of code snippets below in our code base:

我在我们的代码库中看到了很多下面的代码片段:

        try {
            Thread.sleep((int)Millis);
        } catch (InterruptedException e) {
        }

Apparently, an empty catch clause is not a good idea. If the thread is interrupted, the sleep period will not be finished completely.

显然,空的 catch 子句不是一个好主意。如果线程被中断,则休眠期不会完全结束。

I am wondering if there's no logic in my code to interrupt the thread, could JVM interrupt a thread which is sleeping? If so, how to ensure a thread sleep to the end of its specified period?

我想知道我的代码中是否没有中断线程的逻辑,JVM 可以中断正在休眠的线程吗?如果是这样,如何确保线程休眠到其指定时间段的末尾?

And what's the best practice to use thread.sleep()method?

使用thread.sleep()方法的最佳实践是什么?

采纳答案by akhilless

Since comments already link to the answers on the question why you should catch InterruptedException, I will focus on your second question - about the use of Thread.sleep().

由于评论已经链接到关于为什么你应该捕获 InterruptedException 的问题的答案,我将专注于你的第二个问题 - 关于Thread.sleep().

This method is handy when you want to introduce a short pause into your thread execution. For example, imagine you have to update 100 000 rows in a database, but in order to lower the impact on the database you are required to introduce breaks of, say 2 seconds, between your update queries. One of the quick-and-dirty solutions will look like this:

当您想在线程执行中引入短暂的暂停时,此方法很方便。例如,假设您必须更新数据库中的 100 000 行,但为了降低对数据库的影响,您需要在更新查询之间引入间隔,例如 2 秒。一种快速而肮脏的解决方案如下所示:

for (int i = 0; i < 100 000) {
   statement.executeUpdate(....);
   Thread.sleep(2000);
}

Here you after each update you wait 2 seconds and only after that go to executing the next update. (remember is just an illustration of the concept, not full blown production-ready code to be copy-pasted).

每次更新后,您在这里等待 2 秒钟,然后才执行下一次更新。(请记住,这只是概念的一个说明,而不是要复制粘贴的完整的生产就绪代码)。

Another typical situation happens when you wait for some resource to be available and do not want to waste CPU cycles while awaiting for it to become available. For example, you make an asynchronous call that returns a Futureand you want to wait for the the asynchronous computation to complete to go on with your logic. Its generally done like that:

另一种典型情况发生在您等待某些资源可用并且不想在等待它可用时浪费 CPU 周期。例如,您进行了一个返回 a 的异步调用,Future并且您希望等待异步计算完成以继续您的逻辑。它通常是这样做的:

    int someNumberOfMillisToSleep = //some number;
    ...

    while (!future.isDone()) {
        Thread.sleep(someNumberOfMillisToSleep );
    }

    /*now that future.isDone() returned true, 
you can get the result and go on with on with you logic
   */ 
    int res = future.get();

    //some computation here

So having nothing more important to do you sleep waiting for the asynchronous computation to be completed in order not generate useless load on the CPU.

因此,没有什么比等待异步计算完成更重要的事情要做,以免在 CPU 上产生无用的负载。

It is also important that in contrast to waitthe method sleepretains locks on the monitors that were acquired by the thread. That means you can use it in a synchronized block and expect the thread to be able to continue the work it was doing in this block after the sleep returns (of course, if the thread was not interrupted).

wait该方法相比,sleep保持线程获取的监视器上的锁也很重要。这意味着您可以在同步块中使用它,并期望线程能够在睡眠返回后继续它在该块中所做的工作(当然,如果线程没有被中断)。