TimeUnit 使用

TimeUnit是java.util.concurrent包下面的一个类,表示给定单元粒度的时间段

主要作用

  • 时间颗粒度转换
  • 延时

常用的颗粒度

TimeUnit.DAYS          //
TimeUnit.HOURS         //小时
TimeUnit.MINUTES       //分钟
TimeUnit.SECONDS       //
TimeUnit.MILLISECONDS  //毫秒

1.颗粒度转换

public long toMillis(long d)    //转化成毫秒
public long toSeconds(long d)  //转化成秒
public long toMinutes(long d)  //转化成分钟
public long toHours(long d)    //转化成小时
public long toDays(long d)     //转化天
public class Test {
    public static void main(String[] args) {
        //第一种.一天是几个小时
        System.out.println(TimeUnit.DAYS.toHours(1));
        //第二种.一小时是几分钟
        System.out.println(TimeUnit.HOURS.toMinutes(1));
        //第三种.转换成小时把3天,相当于第一种,第二种方式的反写法
        System.out.println(TimeUnit.HOURS.convert(1, TimeUnit.DAYS));
        //第四种.转化成分钟把3小时,相当于第一种,第二种方式的反写法
        System.out.println(TimeUnit.MINUTES.convert(3,TimeUnit.HOURS));
    }
}

2.延时,可替代Thread.sleep()。

public class Test {
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
//                        Thread.sleep(500);//单位是毫秒ms
                        TimeUnit.MILLISECONDS.sleep(500);//和Thread.sleep(500)效果一样,这里的参数都是long类型
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("我打印了:"+i);
                }
            }
        }).start();
    }
}

猜你喜欢

转载自www.cnblogs.com/lzghyh/p/12671199.html