TimeUnit使用

参考网页

http://blog.51cto.com/stevex/1285767

http://www.importnew.com/7219.html

Thread.sleep还是TimeUnit.SECONDS.sleep--使用TimeUnit

TimeUnit可读性更强

举例子,sleep时间为3秒。

Thread.sleep的写法

private final int SLEEP_TIME = 3 * 1000; //3 seconds

void sleepDemo() throws InterruptedException{
    Thread.sleep(SLEEP_TIME);
}

TimeUnit的写法

void sleepDemo() throws InterruptedException{
    TimeUnit.SECONDS.sleep(3);
}

比较--很明显TimeUnit可读性更强

效率上TimeUnit不落下风

示例代码

import java.util.concurrent.TimeUnit;

public class TestSleep {
    public static void main(String[] args) throws InterruptedException {
        sleepByTimeUnit(10);

        sleepByThread(10);
    }

    //使用 TimeUnit 睡 10s
    private static void sleepByTimeUnit(int sleepTimes) throws InterruptedException {
        long start = System.currentTimeMillis();

        TimeUnit.SECONDS.sleep(10);

        long end = System.currentTimeMillis();

        System.out.println("Total time consumed by TimeUnit : " + (end - start));
    }

    //使用 Thread.sleep 睡 10s
    private static void sleepByThread(int sleepTimes) throws InterruptedException {
        long start = System.currentTimeMillis();

        Thread.sleep(10 * 1000);

        long end = System.currentTimeMillis();

        System.out.println("Total time consumed by Thread.sleep : " + (end - start));
    }
}

打印结果

Total time consumed by TimeUnit : 10001

Total time consumed by Thread.sleep : 10015

分析

TimeUnit做了封装,但是相对于 Thread.sleep 效率仍然不落下风。

TimeUnit其他使用--时间转换工具

例子代码

import java.util.concurrent.TimeUnit;

public class TimeUnitUseDemo {
    public static void main(String[] args) {
        long seconds = TimeUnit.HOURS.toSeconds(2);
        System.out.println("Spend seconds:" + seconds);
    }
}

打印结果

Spend seconds:7200

说明

可见,TimeUnit可以被用作时间转换的工具类。

TimeUnit是枚举实现一个很好的实例

TimeUnit 是 Doug Lea 写的,Doug Lea很神

转载于:https://my.oschina.net/u/3866531/blog/2245065

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值