java.util.concurrent.TimeUnit

JavaAPI:https://docs.oracle.com/javase/8/docs/api/index.html


1 TimeUnit

api:https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html

TimeUnit是java.util.concurrent包下面的一个类;TimeUnit 是Java枚举应用场景中最好的例子之一,所有TimeUnit都是枚举实例;

TimeUnit提供了更加优雅的线程sleep写法;TimeUnit还提供了各种时间单位转换的方法;

NANOSECONDS     //毫微秒  十亿分之一秒【1微秒/1000】
MICROSECONDS    //微秒    一百万分之一秒【1毫秒/1000】
MILLISECONDS    //毫秒    千分之一秒    
SECONDS         //秒
MINUTES         //分钟
HOURS           //小时
DAYS            //天
//NANOSECONDS MICROSECONDS MILLISECONDS SECONDS MINUTES HOURS DAYS 
Arrays.stream(TimeUnit.values())
        .forEach((item -> System.out.print(item + " ")));

2 线程睡眠

Modifier and TypeMethod and Description
static voidsleep(long millis)Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
static voidsleep(long millis, int nanos)Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers.

TimeUnit提供了更加优雅的线程睡眠写法

//休眠40分种的三种写法
//
Thread.sleep(2400000);
//
Thread.sleep(40 * 60 * 1000);
// 可读性增强了
TimeUnit.MINUTES.sleep(40);

3 时间单位转换

//sleep 40分组
Thread.sleep(2400000);
 
Thread.sleep(TimeUnit.MINUTES.toMillis(40));
Modifier and TypeMethod and Description
longconvert(long sourceDuration, TimeUnit sourceUnit)Converts the given time duration in the given unit to this unit.
//天转化成小时
TimeUnit.HOURS.convert(3, TimeUnit.DAYS); //72
//小时转化为秒
TimeUnit.SECONDS.convert(1, TimeUnit.HOURS);//3600
Modifier and TypeMethod and Description
longtoDays(long duration)Equivalent to DAYS.convert(duration, this).
//天转化为小时
TimeUnit.DAYS.toHours(3); //72
//小时转化为秒
TimeUnit.HOURS.toSeconds(1); //3600
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Archie_java

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值