TimeUnitはソースコードの解析に深く入り込む


TimeUnitは、JUCパッケージの下に提供される列挙クラスであり、単一要素の粒度が与えられる期間を表す.
例:
まず、TimeUnitのすべての機能を含む例を見てみましょう.
package com.securitit.serialize.juc;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.assertj.core.util.DateUtil;

public class TimeUnitTester {

	public static void main(String[] args) throws Exception {
		//   TimeUnit HOURS    . 24      .
		System.out.println(TimeUnit.HOURS.toDays(24));
		//   TimeUnit DAYS    . 1      .
		System.out.println(TimeUnit.DAYS.toHours(1));
		// Thread.sleep  .
		System.out.println(Thread.currentThread().getName() + ".      .");
		TimeUnit.SECONDS.sleep(1);
		System.out.println(Thread.currentThread().getName() + ".      .");
		// Object.wait  .
		final Object monitor = new Object();
		Thread t1 = new Thread(() -> {
			try {
				System.out.println(Thread.currentThread().getName() + ".          .");
				synchronized (monitor) {
					TimeUnit.SECONDS.timedWait(monitor, 5);
				}
				System.out.println(Thread.currentThread().getName() + ".    ,      .");
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		});
		t1.start();
		// Thread.join  .
		TimeUnit.SECONDS.timedJoin(t1, 1);
		System.out.println(t1.getName() + ".      .");
	}

}

  出力結果:
1
24
main.      .
main.      .
Thread-0.          .
Thread-0.      .
Thread-0..

  出力結果から,TimeUnitは時間に対して処理を行い,同時に比較的汎用的な時間依存操作であり,その独自の時間粒度を用いて二次パッケージを行ったことが分かる.
  ソースコード分析:
時間粒度:
  ・NANOSECONDS-ナノ秒
  ・MICROSECONDS-マイクロ秒
  ・MILLISECONDS-ミリ秒
  ・SECONDS-秒
  ・MINUTES-分
  ・HOURS-時間
  ・DAYS-天
  TimeUnit API:
//    .
public long toNanos(long d);
//    .
public long toMicros(long d);
//    .
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);
//     .
public long convert(long d, TimeUnit u);
//                  .
int excessNanos(long d, long m);
//   Object.wait     .
public void timedWait(Object obj, long timeout) throws InterruptedException {
    if (timeout > 0) {
        long ms = toMillis(timeout);
        int ns = excessNanos(timeout, ms);
        obj.wait(ms, ns);
    }
}
//   Thrad.join     .
public void timedJoin(Thread thread, long timeout)
    throws InterruptedException {
    if (timeout > 0) {
        long ms = toMillis(timeout);
        int ns = excessNanos(timeout, ms);
        thread.join(ms, ns);
    }
}
//   Thread.sleep     .
public void sleep(long timeout) throws InterruptedException {
    if (timeout > 0) {
        long ms = toMillis(timeout);
        int ns = excessNanos(timeout, ms);
        Thread.sleep(ms, ns);
    }
}

  APIでは、toNanos、toMicros、toMillis、toSeconds、toMinutes、toHours、toDays、convert、excessNanosのいくつかのAPIがあり、それぞれの時間粒度の計算方式に違いがあり、中心思想は計算時間であり、論理は複雑ではなく、自分で見ることができる.
 timedWait、timedJoin、sleepは、既存の機能の二次パッケージであり、複雑な時間制限が必要な場合に便利に使用できます.
注記:ソースコードはJDK 1から来ています.8バージョン、バージョンによって異なる場合があります.
どこかわからないことやわからないことがあったら、伝言を歓迎します.