http://blog.51cto.com/stevex/1285767html
http://www.importnew.com/7219.htmljava
舉例子,sleep時間爲3秒。工具
private final int SLEEP_TIME = 3 * 1000; //3 seconds
void sleepDemo() throws InterruptedException{
Thread.sleep(SLEEP_TIME);
}spa
void sleepDemo() throws InterruptedException{
TimeUnit.SECONDS.sleep(3);
}code
import java.util.concurrent.TimeUnit; public class TestSleep { public static void main(String[] args) throws InterruptedException { sleepByTimeUnit(10); sleepByThread(10); } //使用 TimeUnit 睡 10s private static void sleepByTimeUnit(int sleepTimes) throws InterruptedException { long start = System.currentTimeMillis(); TimeUnit.SECONDS.sleep(10); long end = System.currentTimeMillis(); System.out.println("Total time consumed by TimeUnit : " + (end - start)); } //使用 Thread.sleep 睡 10s private static void sleepByThread(int sleepTimes) throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(10 * 1000); long end = System.currentTimeMillis(); System.out.println("Total time consumed by Thread.sleep : " + (end - start)); } }
Total time consumed by TimeUnit : 10001htm
Total time consumed by Thread.sleep : 10015blog
TimeUnit作了封裝,可是相對於 Thread.sleep 效率仍然不落下風。get
import java.util.concurrent.TimeUnit; public class TimeUnitUseDemo { public static void main(String[] args) { long seconds = TimeUnit.HOURS.toSeconds(2); System.out.println("Spend seconds:" + seconds); } }
Spend seconds:7200it
可見,TimeUnit能夠被用做時間轉換的工具類。io