zoukankan      html  css  js  c++  java
  • Java 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)     //转化天
    
    import java.util.concurrent.TimeUnit;
    
    public class TimeUnitTest {
    
        public static void main(String[] args) {
            //convert 1 day to 24 hour
            System.out.println(TimeUnit.DAYS.toHours(1));
            //convert 1 hour to 60*60 second.
            System.out.println(TimeUnit.HOURS.toSeconds(1));
            //convert 3 days to 72 hours.
            System.out.println(TimeUnit.HOURS.convert(3, TimeUnit.DAYS));
        }
    
    }

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

    import java.util.concurrent.TimeUnit;
    
    public class ThreadSleep {
    
        public static void main(String[] args) {
            Thread t = new Thread(new Runnable() {
                private int count = 0;
    
                @Override
                public void run() {
                    for (int i = 0; i < 10; i++) {
                        try {
                            // Thread.sleep(500); //sleep 单位是毫秒
                            TimeUnit.SECONDS.sleep(1); // 单位可以自定义,more convinent
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        count++;
                        System.out.println(count);
                    }
                }
            });
            t.start();
        }
    }


    作者:有苦向瓜诉说
    链接:https://www.jianshu.com/p/4ab62e4a328f
    来源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。



  • 相关阅读:
    医疗设备软件的安全性问答
    python使用技巧
    C++对象模型
    面向对象方法综述
    如何设计可扩展性系统架构
    敏捷过程
    python中import的相关知识总结
    软件架构的关键原则
    读后感——程序员的思维修炼
    LINUX系统备份工具
  • 原文地址:https://www.cnblogs.com/h-c-g/p/10725911.html
Copyright © 2011-2022 走看看