1. 程式人生 > 其它 >TimeUnit和Thread.sleep()

TimeUnit和Thread.sleep()

技術標籤:java

TimeUnit是java.util.concurrent包下的一個列舉類.
官方介紹:

A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units. A TimeUnit does not maintain time information, but only helps organize and use time representations that may be maintained separately across various contexts. A nanosecond is defined as one thousandth of a microsecond, a microsecond as one thousandth of a millisecond, a millisecond as one thousandth of a second, a minute as sixty seconds, an hour as sixty minutes, and a day as twenty four hours.
A TimeUnit is mainly used to inform time-based methods how a given timing parameter should be interpreted. For example, the following code will timeout in 50 milliseconds if the lock is not available:

ATimeUnit表示給定粒度單位的持續時間,並提供實用方法以在各個單位之間進行轉換,並在這些單位中執行計時和延遲操作。
ATimeUnit主要用於告知基於時間的方法應如何解釋給定的時序引數。

相比於Thread.sleep而言,使用TimeUnit列舉類更加清楚易懂.

Thread.sleep(1000); //1s

TimeUnit.SECONDS.sleep(1);//1s

TimeUnit有許多列舉常量供我們使用,NANOSECONDS、MICROSECONDS、MILLISECONDS、SECONDS、MINUTES、HOURS、DAYS