欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java日期时间API系列5-----Jdk7及以前的日期时间类TimeUnit在并发编程中的应用

程序员文章站 2023-11-02 16:18:16
TimeUnit是一个时间单位枚举类,主要用于并发编程,时间单元表示给定粒度单元的时间持续时间,并提供实用程序方法来跨单元转换,以及在这些单元中执行计时和延迟操作。 1.时间单位换算 (1)支持的单位 TimeUnit.DAYS //天 TimeUnit.HOURS //小时 TimeUnit.MI ......

timeunit是一个时间单位枚举类,主要用于并发编程,时间单元表示给定粒度单元的时间持续时间,并提供实用程序方法来跨单元转换,以及在这些单元中执行计时和延迟操作。

1.时间单位换算

(1)支持的单位

timeunit.days          //天
timeunit.hours         //小时
timeunit.minutes       //分钟
timeunit.seconds       //秒
timeunit.milliseconds  //毫秒
timeunit.microseconds  //微秒
timeunit.nanoseconds  //纳秒

(2)转换方法,例如:timeunit.hours 的转换源码

    hours {
        public long tonanos(long d)   { return x(d, c5/c0, max/(c5/c0)); }
        public long tomicros(long d)  { return x(d, c5/c1, max/(c5/c1)); }
        public long tomillis(long d)  { return x(d, c5/c2, max/(c5/c2)); }
        public long toseconds(long d) { return x(d, c5/c3, max/(c5/c3)); }
        public long tominutes(long d) { return x(d, c5/c4, max/(c5/c4)); }
        public long tohours(long d)   { return d; }
        public long todays(long d)    { return d/(c6/c5); }
        public long convert(long d, timeunit u) { return u.tohours(d); }
        int excessnanos(long d, long m) { return 0; }
    }

(3)使用举例

//小时转换为秒
long sec = timeunit.hours.toseconds(1);
system.out.println("sec:" + sec);

// 另一种形式
long sec2 = timeunit.seconds.convert(1, timeunit.hours);
system.out.println("sec2:" + sec2);

输出结果:

sec:3600
sec2:3600

 

2.计时操作

(1)例如:尝试获取锁50毫秒

  lock lock = ...;
   if (lock.trylock(50l, timeunit.milliseconds)) ...

 

3.延迟操作

(1)比如当前线程延迟5s

timeunit.seconds.sleep(5);

 

4.timeunit 与 thread sleep的区别

(1)timeunit sleep的原理

    public void sleep(long timeout) throws interruptedexception {
        if (timeout > 0) {
            long ms = tomillis(timeout);
            int ns = excessnanos(timeout, ms);
            thread.sleep(ms, ns);
        }
    }

timeunit sleep的底层调用了thread.sleep。

(2)区别:timeunit sleep使用起来更方便,更易懂

比如:比如当前线程延迟5s:

使用thread.sleep

thread.sleep(5000);
// 或者
thread.sleep(5*1000);

使用timeunit

timeunit.seconds.sleep(5);