Java TimeUnit Calculate sleep(long pTime, TimeUnit pTimeUnit)

Here you can find the source of sleep(long pTime, TimeUnit pTimeUnit)

Description

sleep

License

Open Source License

Declaration

public static final void sleep(long pTime, TimeUnit pTimeUnit) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.concurrent.TimeUnit;

public class Main {
    public static final void sleep(long pTime, TimeUnit pTimeUnit) {
        final long lStart = System.nanoTime();
        long lDeadlineInNanos = lStart + pTimeUnit.toNanos(pTime);

        boolean lSleepTimeBelowMillisecond = pTimeUnit.toMillis(pTime) == 0;

        long lNanoTime;
        while ((lNanoTime = System.nanoTime()) < lDeadlineInNanos) {

            try {
                if (lSleepTimeBelowMillisecond) {
                    long lTimeToWaitInNanos = 3 * (lDeadlineInNanos - lNanoTime) / 4;
                    if (lTimeToWaitInNanos > 0)
                        Thread.sleep(0, (int) lTimeToWaitInNanos);
                } else {
                    long lTimeToWaitInNanos = 3 * (lDeadlineInNanos - lNanoTime) / 4;
                    if (lTimeToWaitInNanos > 0) {
                        long lTimeToWaitInMillis = TimeUnit.NANOSECONDS.toMillis(lTimeToWaitInNanos);

                        Thread.sleep(lTimeToWaitInMillis, (int) (lTimeToWaitInNanos % 1000000L));
                    }//from  w  ww  .  j  av a2s. c o  m
                }
            } catch (InterruptedException e) {
            }
        }
    }
}

Related

  1. run(final Runnable runnable, long timeout, TimeUnit unit)
  2. shortName(TimeUnit unit)
  3. sleep(int duration, TimeUnit unit)
  4. sleep(long duration, TimeUnit timeUnit)
  5. sleep(long duration, TimeUnit timeUnit)
  6. sleep(TimeUnit timeUnit, long duration)
  7. sleep(TimeUnit unit, long length)
  8. sleepAndCachedInterruptedException(long sleepFor, TimeUnit unit)
  9. sleepFor(long period, TimeUnit timeUnit)