bfchengnuo / MyRecord

平时充电做的笔记,一个程序猿的自我修养.
https://bfchengnuo.com/MyRecord/
33 stars 8 forks source link

TimeUnit 工具类相关(JUC) #33

Closed bfchengnuo closed 5 years ago

bfchengnuo commented 5 years ago

TimeUnit 是 JUC(java.util.concurrent)下面的一个类,表示给定单元粒度的时间段。

最常用的:

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));
    }
}

TimeUnit 提供了可读性更好的线程暂停操作,通常用来替换 Thread.sleep()

public class ThreadSleep {
    public static void main(String[] args) {
        new Thread(() -> {
            try {
                // Thread.sleep(500); //sleep 单位是毫秒
                TimeUnit.SECONDS.sleep(1); // 单位可以自定义,more convinent
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}