概述
TimeUnit 是一个表示以给定单位的粒度表示时间持续时间的类,并提供转换单位的实用方法以及在这些单位中执行定时和延迟操作。 TimeUnit 不会维护时间信息,而只会帮助组织和使用可能在各种上下文中单独维护的时间表示。 纳秒被定义为微秒的千分之一,微秒被定义为毫秒的千分之一,毫秒被定义为秒的千分之一,分钟被定义为 60 秒,小时被定义为 60 分钟,天被定义为 24 小时。 TimeUnit 主要用于告知基于时间的方法应该如何解释给定的计时参数。 例如,以下代码将在 50 毫秒内超时,如果锁不可用:
Lock lock = ...;
if (lock.tryLock(50L, TimeUnit.MILLISECONDS)) ...
while this code will timeout in 50 seconds:
Lock lock = ...;
if (lock.tryLock(50L, TimeUnit.SECONDS)) ...
但是请注意,特定的超时实现并不能保证以与给定的 TimeUnit 相同的粒度注意到时间的流逝。
用例
public class TimeUnitTest {
@Test
public void testConvert(){
long seconds =TimeUnit.SECONDS.convert(1,TimeUnit.HOURS);
//1小时转换为秒
Assert.assertEquals(3600,seconds);
//1分钟转为秒
long minutes =TimeUnit.SECONDS.convert(1,TimeUnit.MINUTES);
Assert.assertEquals(60,minutes);
}
@Test
public void testConvertDuration(){
long convert = TimeUnit.MILLISECONDS.convert(Duration.of(1, ChronoUnit.SECONDS));
//1秒转换为毫秒
Assert.assertEquals(1000,convert);
}
@Test
public void testOf(){
//1天转换为小时
long hours = TimeUnit.of(ChronoUnit.DAYS).toHours(1);
Assert.assertEquals(24,hours);
}
@Test
public void testTimeWait() throws InterruptedException {
Object lock = new Object();
synchronized (lock) {
long now = System.nanoTime();
TimeUnit.SECONDS.timedWait(lock, 1);
long nanos = System.nanoTime() - now;
//1010055500 大约为1秒
System.out.println(nanos);
}
}
@Test
public void testTimedJoin() throws InterruptedException {
Thread t = new Thread(()->{
for(;;){
}
});
t.start();
System.out.println("start wait");
//子线程t等待10秒
TimeUnit.SECONDS.timedJoin(t, 10);
System.out.println("end wait");
}
}
分享到: