相关文章:
这次主要整理下 Java 中 TimeUnit 类的常用方法
一、TimeUnit类的定义
-
TimeUnit 类位于 java.util.concurrent 包中,是一个枚举类,主要用于时间颗粒度的转换与线程的延时
-
TimeUnit 包含以下七个枚举常量
常量名 含义 NANOSECONDS 纳秒,等于 $1 * 10^{-9}s$
MICROSECONDS 微秒,等于 $1 * 10^{-6}s$
MILLISECONDS 毫秒,等于 $1 * 10^{-3}s$
SECONDS 秒 MINUTES 分 HOURS 时 DAYS 日
二、TimeUnit 类常用方法
-
toDays(long duration)
-
将指定颗粒度的时间转换为天数
// 将1天转换为天数 System.out.println(TimeUnit.DAYS.toDays(1)); // 1
-
-
toHours(long duration)
-
将指定颗粒度的时间转换为小时数
// 将1天转换为小时数 System.out.println(TimeUnit.DAYS.toHours(1)); // 24
-
-
toMinutes(long duration)
-
将指定颗粒度的时间转换为分数
// 将1天转换为分数 System.out.println(TimeUnit.DAYS.toMinutes(1)); // 1440
-
-
toSeconds(long duration)
-
将指定颗粒度的时间转换为秒数
// 将1天转换为秒数 System.out.println(TimeUnit.DAYS.toSeconds(1)); // 86400
-
-
toMillis(long duration)
-
将指定颗粒度的时间转换为毫秒数
// 将1天转换为毫秒数 System.out.println(TimeUnit.DAYS.toMillis(1)); // 86400000
-
-
toMicros(long duration)
-
将指定颗粒度的时间转换为微秒数
// 将1天转换为微秒数 System.out.println(TimeUnit.DAYS.toMicros(1)); // 86400000000
-
-
toNanos(long duration)
-
将指定颗粒度的时间转换为纳秒数
// 将1天转换为纳秒数 System.out.println(TimeUnit.DAYS.toNanos(1)); // 86400000000000
-
-
convert(long sourceDuration, TimeUnit sourceUnit)
-
将参数颗粒度时间转换为指定颗粒度时间
// 将48小时转换为天数 System.out.println(TimeUnit.DAYS.convert(48, TimeUnit.HOURS)); // 2
-
-
compareTo(E o)
-
比较两个枚举常量的索引值大小,返回一个差值
// [NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS] System.out.println(Arrays.toString(TimeUnit.values())); // DAYS的索引值为6 System.out.println(TimeUnit.DAYS.ordinal()); //6 // MINUTES的索引值为4 System.out.println(TimeUnit.MINUTES.ordinal()); // 4 System.out.println(TimeUnit.DAYS.compareTo(TimeUnit.MINUTES)); // 2 System.out.println(TimeUnit.MINUTES.compareTo(TimeUnit.DAYS)); // -2
-
-
sleep(long timeout)
-
提供了可读性更好的线程休眠操作,使线程休眠指定时间颗粒度的时间,通常用来替换 Thread.sleep()
-
当使用 Thread.sleep() 方法时,由于输入的参数为毫秒数,所以很难直观地看出当前线程具体休眠了多长时间
Thread.sleep(2000); // 休眠2秒钟 (时间颗粒度为秒) TimeUnit.SECONDS.sleep(2); // 休眠2分钟 (时间颗粒度为分) TimeUnit.MINUTES.sleep(2)
-
-
timedJoin(Thread thread, long timeout)
-
对指定线程,休眠指定时间颗粒度的时间
// 对当前线程休眠2秒 TimeUnit.SECONDS.timedJoin(Thread.currentThread(), 2);
-
-
timedWait(Object obj, long timeout)
-
对指定对象,休眠指定时间颗粒度的时间
public class Test { // 此处需要使用synchronized关键字将方法锁住 public synchronized void show() throws InterruptedException { TimeUnit.SECONDS.timedWait(this, 2); System.out.println("HelloWorld"); } public static void main(String[] args) throws InterruptedException { Test test = new Test(); // 2秒之后执行 test.show(); } }
-