Java : TimeUnit - API使用例
TimeUnit (Java SE 18 & JDK 18) の使用例まとめです。
だいたいのメソッドを網羅済みです。
API仕様のおともにどうぞ。
概要
TimeUnit は、時間の単位を表す列挙型です。
列挙子には
- 日 (DAYS)
- 時 (HOURS)
- 分 (MINUTES)
- 秒 (SECONDS)
- ミリ秒 (MILLISECONDS)
- マイクロ秒 (MICROSECONDS)
- ナノ秒 (NANOSECONDS)
があります。
主に、スレッド関連のAPIで、待機時間などを指定するときに、その時間単位として使われます。
final var executorService = Executors.newSingleThreadExecutor();
try {
final var future = executorService.submit(() -> "abcd");
final var ret = future.get();
System.out.println(ret); // abcd
} finally {
executorService.shutdown();
}
final var ret = executorService.awaitTermination(1, TimeUnit.MINUTES);
System.out.println(ret); // true
TimeUnit は列挙型ですが、いくつかのユーティリティ・メソッドが提供されています。
おすすめは sleep メソッドです。Thread.sleep の代わりに TimeUnit の sleep を使うと、時間の単位が明確になりソースコードの可読性が(少し)よくなります。
final var start = System.nanoTime();
// Thread.sleep(5000) と同じ意味です。
TimeUnit.SECONDS.sleep(5);
final var end = System.nanoTime();
// 5.001643 sec.
System.out.printf("%f sec.%n", (end - start) / 1000000000.0);
列挙型定数
DAYS
System.out.println(TimeUnit.DAYS); // DAYS
System.out.println(TimeUnit.DAYS.toHours(1)); // 24
HOURS
System.out.println(TimeUnit.HOURS); // HOURS
System.out.println(TimeUnit.HOURS.toMinutes(1)); // 60
MICROSECONDS
System.out.println(TimeUnit.MICROSECONDS); // MICROSECONDS
System.out.println(TimeUnit.MICROSECONDS.toNanos(1)); // 1000
MILLISECONDS
System.out.println(TimeUnit.MILLISECONDS); // MILLISECONDS
System.out.println(TimeUnit.MILLISECONDS.toMicros(1)); // 1000
MINUTES
System.out.println(TimeUnit.MINUTES); // MINUTES
System.out.println(TimeUnit.MINUTES.toSeconds(1)); // 60
NANOSECONDS
System.out.println(TimeUnit.NANOSECONDS); // NANOSECONDS
System.out.println(TimeUnit.NANOSECONDS.toSeconds(1000000000)); // 1
SECONDS
System.out.println(TimeUnit.SECONDS); // SECONDS
System.out.println(TimeUnit.SECONDS.toMillis(1)); // 1000
メソッド
long convert (long sourceDuration, TimeUnit sourceUnit)
final var ret1 = TimeUnit.HOURS.convert(1, TimeUnit.DAYS);
System.out.println(ret1); // 24
final var ret2 = TimeUnit.MINUTES.convert(2, TimeUnit.HOURS);
System.out.println(ret2); // 120
final var ret3 = TimeUnit.MILLISECONDS.convert(3, TimeUnit.SECONDS);
System.out.println(ret3); // 3000
final var ret1 = TimeUnit.SECONDS.convert(1000, TimeUnit.MILLISECONDS);
System.out.println(ret1); // 1
final var ret2 = TimeUnit.SECONDS.convert(999, TimeUnit.MILLISECONDS);
System.out.println(ret2); // 0
// オーバーフローの例です。
final var ret1 = TimeUnit.NANOSECONDS.convert(100000000, TimeUnit.DAYS);
System.out.println(ret1 == Long.MAX_VALUE); // true
final var ret2 = TimeUnit.NANOSECONDS.convert(-100000000, TimeUnit.DAYS);
System.out.println(ret2 == Long.MIN_VALUE); // true
long convert (Duration duration)
final var ret1 = TimeUnit.HOURS.convert(Duration.ofDays(1));
System.out.println(ret1); // 24
final var ret2 = TimeUnit.MINUTES.convert(Duration.ofHours(2));
System.out.println(ret2); // 120
final var ret3 = TimeUnit.MILLISECONDS.convert(Duration.ofSeconds(3));
System.out.println(ret3); // 3000
static TimeUnit of (ChronoUnit chronoUnit)
final var ret1 = TimeUnit.of(ChronoUnit.DAYS);
System.out.println(ret1); // DAYS
final var ret2 = TimeUnit.of(ChronoUnit.SECONDS);
System.out.println(ret2); // SECONDS
void sleep (long timeout)
final var start = System.nanoTime();
// Thread.sleep(5000) と同じ意味です。
TimeUnit.SECONDS.sleep(5);
final var end = System.nanoTime();
// 5.001643 sec.
System.out.printf("%f sec.%n", (end - start) / 1000000000.0);
final var start = System.nanoTime();
TimeUnit.MINUTES.sleep(1);
final var end = System.nanoTime();
// 60.000510 sec.
System.out.printf("%f sec.%n", (end - start) / 1000000000.0);
void timedJoin (Thread thread, long timeout)
final var thread = new Thread(() -> {
try {
System.out.println("task : start");
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
System.out.println("Interrupted!");
} finally {
System.out.println("task : end");
}
});
System.out.println("-- start --");
thread.start();
System.out.println("-- join start --");
TimeUnit.SECONDS.timedJoin(thread, 3);
System.out.println("-- join end --");
// 結果
// ↓
//-- start --
//-- join start --
//task : start
//task : end
//-- join end --
void timedWait (Object obj, long timeout)
// 基準となる時刻
final long current = System.nanoTime();
// 基準となる時刻からの差分を秒として取得
final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;
final var executorService = Executors.newSingleThreadExecutor();
try {
final var obj = new Object();
final Callable<Void> task = () -> {
try {
System.out.printf("task start : %f sec.%n", elapsedSec.getAsDouble());
synchronized (obj) {
TimeUnit.SECONDS.timedWait(obj, 2);
}
} finally {
System.out.printf("task end : %f sec.%n", elapsedSec.getAsDouble());
}
return null;
};
executorService.submit(task);
TimeUnit.SECONDS.sleep(5);
synchronized (obj) {
obj.notify();
}
} finally {
executorService.shutdown();
System.out.printf("--- shutdown --- : %f sec.%n", elapsedSec.getAsDouble());
}
final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.printf("termination %b : %f sec.%n", ret, elapsedSec.getAsDouble());
// 結果
// ↓
//task start : 0.002766 sec.
//task end : 2.016894 sec.
//--- shutdown --- : 5.031749 sec.
//termination true : 5.033790 sec.
ChronoUnit toChronoUnit ()
final var ret1 = TimeUnit.HOURS.toChronoUnit();
System.out.println(ret1); // Hours
final var ret2 = TimeUnit.MINUTES.toChronoUnit();
System.out.println(ret2); // Minutes
final var ret3 = TimeUnit.SECONDS.toChronoUnit();
System.out.println(ret3); // Seconds
long toDays (long duration)
final var ret1 = TimeUnit.HOURS.toDays(48);
System.out.println(ret1); // 2
final var ret2 = TimeUnit.MINUTES.toDays(24 * 60 * 10);
System.out.println(ret2); // 10
long toHours (long duration)
final var ret1 = TimeUnit.DAYS.toHours(1);
System.out.println(ret1); // 24
final var ret2 = TimeUnit.MINUTES.toHours(60 * 10);
System.out.println(ret2); // 10
long toMicros (long duration)
final var ret1 = TimeUnit.MILLISECONDS.toMicros(1);
System.out.println(ret1); // 1000
final var ret2 = TimeUnit.NANOSECONDS.toMicros(1000 * 50);
System.out.println(ret2); // 50
long toMillis (long duration)
final var ret1 = TimeUnit.SECONDS.toMillis(1);
System.out.println(ret1); // 1000
final var ret2 = TimeUnit.MICROSECONDS.toMillis(1000 * 50);
System.out.println(ret2); // 50
long toMinutes (long duration)
final var ret1 = TimeUnit.HOURS.toMinutes(1);
System.out.println(ret1); // 60
final var ret2 = TimeUnit.SECONDS.toMinutes(60 * 150);
System.out.println(ret2); // 150
long toNanos (long duration)
final var ret1 = TimeUnit.MICROSECONDS.toNanos(1);
System.out.println(ret1); // 1000
final var ret2 = TimeUnit.MILLISECONDS.toNanos(5);
System.out.println(ret2); // 5000000
long toSeconds (long duration)
final var ret1 = TimeUnit.MINUTES.toSeconds(1);
System.out.println(ret1); // 60
final var ret2 = TimeUnit.MILLISECONDS.toSeconds(1000 * 150);
System.out.println(ret2); // 150
static TimeUnit valueOf (String name)
final var ret1 = TimeUnit.valueOf("DAYS");
System.out.println(ret1); // DAYS
final var ret2 = TimeUnit.valueOf("SECONDS");
System.out.println(ret2); // SECONDS
static TimeUnit[] values ()
for (final var value : TimeUnit.values()) {
System.out.println(value);
}
// 結果
// ↓
//NANOSECONDS
//MICROSECONDS
//MILLISECONDS
//SECONDS
//MINUTES
//HOURS
//DAYS
Enumで宣言されたメソッド
clone, compareTo, describeConstable, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf
「Java API 使用例 : Enum」をご参照ください。
関連記事
- API 使用例
- BlockingQueue (ブロッキング・キュー)
- Callable
- CancellationException
- ConcurrentHashMap.KeySetView (並列処理用セット)
- ConcurrentLinkedDeque (並列処理用・両端キュー)
- ConcurrentLinkedQueue (並列処理用キュー)
- ConcurrentMap (並列処理用マップ)
- ConcurrentModificationException (並列処理例外)
- ConcurrentSkipListSet (並列処理用セット)
- Condition (同期)
- CopyOnWriteArrayList (並列処理用リスト)
- CopyOnWriteArraySet (並列処理用セット)
- CountDownLatch (同期)
- CyclicBarrier (同期)
- Exchanger (同期)
- Executor
- ExecutorService
- Executors
- Future
- Future.State
- FutureTask
- InterruptedException (割込み例外)
- Lock (同期)
- Object (オブジェクト)
- Runnable
- Semaphore (セマフォ)
- Thread (スレッド)
- ThreadGroup
- ThreadLocal