TimeUnit使用

參考網頁

http://blog.51cto.com/stevex/1285767html

http://www.importnew.com/7219.htmljava

Thread.sleep仍是TimeUnit.SECONDS.sleep--使用TimeUnit

TimeUnit可讀性更強

舉例子,sleep時間爲3秒。工具

Thread.sleep的寫法

private final int SLEEP_TIME = 3 * 1000; //3 seconds

void sleepDemo() throws InterruptedException{
    Thread.sleep(SLEEP_TIME);
}
spa

TimeUnit的寫法

void sleepDemo() throws InterruptedException{
    TimeUnit.SECONDS.sleep(3);
}
code

比較--很明顯TimeUnit可讀性更強

效率上TimeUnit不落下風

示例代碼

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

TimeUnit其餘使用--時間轉換工具

例子代碼

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

TimeUnit是枚舉實現一個很好的實例

TimeUnit 是 Doug Lea 寫的,Doug Lea很神

相關文章
相關標籤/搜索