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) //轉化天
例子
package com.app;
import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) {
//1天有24個小時 1代表1天:將1天轉化為小時
System.out.println( TimeUnit.DAYS.toHours( 1 ) );
//結果: 24
//1小時有3600秒
System.out.println( TimeUnit.HOURS.toSeconds( 1 ));
//結果3600
//把3天轉化成小時
System.out.println( TimeUnit.HOURS.convert( 3 , TimeUnit.DAYS ) );
//結果是:72
}
}
2、延時
- 一般的寫法
package com.app;
public class Test2 {
public static void main(String[] args) {
new Thread( new Runnable() {
@Override
public void run() {
try {
Thread.sleep( 5 * 1000 );
System.out.println( "延時完成了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start(); ;
}
}
- TimeUnit 寫法
package com.app;
import java.util.concurrent.TimeUnit;
public class Test2 {
public static void main(String[] args) {
new Thread( new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep( 5 );
System.out.println( "延時5秒,完成了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start(); ;
}
}
