Java TimeUnit的使用

目录

简易的日期工具类,位于java.util.concurrent包下。

1
2
3
4
5
6
7
8
9
10
11
// 一些用法
TimeUnit.SECONDS.toMillis(1) 1秒转换为毫秒数
TimeUnit.SECONDS.toMinutes(60) 60秒转换为分钟数
TimeUnit.SECONDS.sleep(5) 线程休眠5秒
TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES) 1分钟转换为秒数

//TimeUnit.DAYS 日的工具类
//TimeUnit.HOURS 时的工具类
//TimeUnit.MINUTES 分的工具类
//TimeUnit.SECONDS 秒的工具类
//TimeUnit.MILLISECONDS 毫秒的工具类

TimeUnit提供了更优雅的线程sleep、timeJoin操作,通常用来替换Thread.sleep(),Thread.join()。
例子:

1
2
3
4
5
// 使用Thread sleep:
Thread.sleep(4 * 60 * 1000);

// 使用TimeUnit
TimeUnit.MINUTES.sleep(4);

TimeUnit中的sleep方法内部调用的也是Thread.sleep(..), timeJoin同理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void sleep(long timeout) throws InterruptedException {
if (timeout > 0) {
long ms = toMillis(timeout);
int ns = excessNanos(timeout, ms);
Thread.sleep(ms, ns);
}
}

public void timedJoin(Thread thread, long timeout)
throws InterruptedException {
if (timeout > 0) {
long ms = toMillis(timeout);
int ns = excessNanos(timeout, ms);
thread.join(ms, ns);
}
}