java併發包中的TimeUnit的使用
阿新 • • 發佈:2019-01-09
在學java多執行緒時,發現在關於時間的設定時,有個列舉會經常用到,這個列舉就是TimeUnit。對此產生了興趣,查閱網上資料與原始碼後,記錄下學到的知識,以便下次看部落格時記起來:
首先 TimeUnit是java.util.concurrent包下面的一個類,表示給定單元粒度的時間段
一、主要作用
a.時間顆粒度轉換
b.延時
二、舉個例子
-
常用的顆粒度
TimeUnit.DAYS //天
TimeUnit.HOURS //小時
TimeUnit.MINUTES //分鐘
TimeUnit.SECONDS //秒
TimeUnit.MILLISECONDS //毫秒
常用方法:
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
}
}
- 延時
一般的寫法
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(); ;
}
}