關於TimeUnit使用和解析

TimeUnit是java.util.concurrent包下面的一個類,表示給定單元粒度的時間段

 主要作用

         時間顆粒度轉換

         延時

1.常用的顆粒度

TimeUnit.DAYS          //天
TimeUnit.HOURS         //小時
TimeUnit.MINUTES       //分鐘
TimeUnit.SECONDS       //秒
TimeUnit.MILLISECONDS  //毫秒

2.顆粒度轉換

public long toMillis(long d)    //轉化成毫秒
public long toSeconds(long d)  //轉化成秒
public long toMinutes(long d)  //轉化成分鐘
public long toHours(long d)    //轉化成小時
public long toDays(long d)     //轉化天
import java.util.concurrent.TimeUnit;

public class TimeUnitTest {

    public static void main(String[] args) {
        //convert 1 day to 24 hour
        System.out.println(TimeUnit.DAYS.toHours(1));
        //convert 1 hour to 60*60 second.
        System.out.println(TimeUnit.HOURS.toSeconds(1));
        //convert 3 days to 72 hours.
        System.out.println(TimeUnit.HOURS.convert(3, TimeUnit.DAYS));
    }

}

3.延時,可替代Thread.sleep()。

import java.util.concurrent.TimeUnit;

public class ThreadSleep {

    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            private int count = 0;

            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        // Thread.sleep(500); //sleep 單位是毫秒
                        TimeUnit.SECONDS.sleep(1); // 單位可以自定義,more convinent
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count++;
                    System.out.println(count);
                }
            }
        });
        t.start();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章