剛看到TimeUnit.SECONDS.sleep()方法時覺得挺奇怪的,這裡怎麼也提供sleep方法?
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枚舉成員的方法卻提供更好的可讀性,這可能就是當初創建TimeUnit時提供sleep方法的原因吧,大家都知道sleep方法很常用,但經常要使用一個常量保存sleep的時間,比如3秒鐘,我們代碼通常會這樣寫:
private final int SLEEP_TIME = 3 * 1000; //3 seconds
因為Thread.sleep方法參數接受的毫秒單位的數值,比較下面代碼就知道TimeUnit枚舉成員的sleep方法更優雅:
TimeUnit.MILLISECONDS.sleep(10); TimeUnit.SECONDS.sleep(10); TimeUnit.MINUTES.sleep(10); Thread.sleep(10); Thread.sleep(10*1000); Thread.sleep(10*60*1000);
但使用TimeUnit枚舉成員的sleep方法會不會帶來性能損失了,畢竟增加了函數調用開銷?
測試測試吧:
import java.util.concurrent.TimeUnit; public class TestSleep { public static void main(String[] args) throws InterruptedException { sleepByTimeunit(10000); sleepByThread(10000); } private static void sleepByTimeunit(int sleepTimes) throws InterruptedException { long start = System.currentTimeMillis(); for(int i=0; i<sleepTimes; i++){ TimeUnit.MILLISECONDS.sleep(10); } long end = System.currentTimeMillis(); System.out.println("Total time consumed by TimeUnit.MILLISECONDS.sleep : " + (end - start)); } private static void sleepByThread(int sleepTimes) throws InterruptedException { long start = System.currentTimeMillis(); for(int i=0; i<sleepTimes; i++){ Thread.sleep(10); } long end = System.currentTimeMillis(); System.out.println("Total time consumed by Thread.sleep : " + (end - start)); } }
兩次測試結果(Win7+4G+JDK7 測試期間計算資源充足):
Total time consumed by TimeUnit.MILLISECONDS.sleep : 100068 Total time consumed by Thread.sleep : 100134 Difference : -- -66 Total time consumed by TimeUnit.MILLISECONDS.sleep : 100222 Total time consumed by Thread.sleep : 100077 Difference : -- +145
從結果可以看出10000次調用差異很小,甚至一次更快,不排除JVM進行了優化,如果忽略性能方面考慮,從可讀性方面建議使用TimeUnit枚舉成員的sleep方法。
另外TimeUnit是枚舉實現一個很好的實例,Doug Lea太神了,佩服得五體投地!
出處:http://stevex.blog.51cto.com/4300375/1285767