TimeUnit.SECONDS.sleep()和sleep區別
剛看到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