Thread.sleep与TimeUnit.SECONDS.sleep [英] Thread.sleep vs. TimeUnit.SECONDS.sleep

查看:254
本文介绍了Thread.sleep与TimeUnit.SECONDS.sleep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我打算让一个Java线程进入睡眠状态,是否有理由更喜欢其中一种形式?

If I'm going to have a call to have a Java Thread go to sleep, is there a reason to prefer one of these forms over the other?

Thread.sleep(x)

TimeUnit.SECONDS.sleep(y)


推荐答案

TimeUnit.SECONDS.sleep(x) 将调用 Thread.sleep
唯一的区别是可读性和使用对于非显而易见的持续时间, TimeUnit 可能更容易理解(例如: Thread.sleep(180000) vs. TimeUnit.MINUTES.sleep(3))。

TimeUnit.SECONDS.sleep(x) will call Thread.sleep. The only difference is readability and using TimeUnit is probably easier to understand for non obvious durations (for example: Thread.sleep(180000) vs. TimeUnit.MINUTES.sleep(3)).

作为参考,请参阅下面中的代码 TimeUnit

For reference, see below the code of sleep() in TimeUnit:

public void sleep(long timeout) throws InterruptedException {
    if (timeout > 0) {
        long ms = toMillis(timeout);
        int ns = excessNanos(timeout, ms);
        Thread.sleep(ms, ns);
    }
}

这篇关于Thread.sleep与TimeUnit.SECONDS.sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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