TimeUnit基本用法

307 阅读1分钟

TimeUnit介绍

TimeUnit是JDK封装好的java.util.concurrent包下面的一个类,表示给定单元粒度的时间段

TimeUnit的作用

1.时间颗粒度转换

常用的所有的颗粒度

TimeUnit.DAYS //天 TimeUnit.HOURS //小时 TimeUnit.MINUTES //分钟 TimeUnit.SECONDS //秒 TimeUnit.MILLISECONDS //毫秒 TimeUnit.MICROSSECONDS //微秒 TimeUnit.NANOSSECONDS //纳秒

方式一: 用常用的转换方法

public long toDays(long d)     //转化成天
public long toHours(long d)    //转化成小时
public long toMinutes(long d)  //转化成分钟
public long toSeconds(long d)  //转化成秒
public long toMillis(long d)    //转化成毫秒
//时间颗粒度转换方式一
long toHours = TimeUnit.DAYS.toHours(1);
System.out.println("1天转化为:"+toHours+"小时");
​
long toMinutes = TimeUnit.HOURS.toMinutes(1);
System.out.println("1小时转化为:"+toMinutes+"分钟");
​
long toSeconds = TimeUnit.MINUTES.toSeconds(1);
System.out.println("1分钟转化为:"+toSeconds+"秒");
​
long toMillis = TimeUnit.SECONDS.toMillis(1);
System.out.println("1秒钟转化为:"+toMillis+"毫秒");

运行结果:

1天转化为:24小时 1小时转化为:60分钟 1分钟转化为:60秒 1秒钟转化为:1000毫秒

方式二: 使用convert

//转换方式二 convert
long convert = TimeUnit.HOURS.convert(1, TimeUnit.DAYS);
System.out.println(convert);

运行结果: 24

2.线程延时

try {
    long start = System.currentTimeMillis();
    //让线程睡眠5秒钟
    TimeUnit.SECONDS.sleep(5);
    long end = System.currentTimeMillis();
    System.out.println("执行时间为"+(end-start)+"ms"); //执行时间为5001ms
} catch (InterruptedException e) {
    throw new RuntimeException(e);
}