Java TimeUnit Usage sleepNanos(long nanoDuration)

Here you can find the source of sleepNanos(long nanoDuration)

Description

sleep Nanos

License

Open Source License

Declaration

public static void sleepNanos(long nanoDuration) throws InterruptedException 

Method Source Code

//package com.java2s;
/*/*from   w w w  .j  a  v  a  2  s  . c  o m*/
 * gMix open source project - https://svs.informatik.uni-hamburg.de/gmix/
 * Copyright (C) 2012  Karl-Peter Fuchs
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.concurrent.TimeUnit;

public class Main {
    private static final long SLEEP_PRECISION = TimeUnit.MILLISECONDS.toNanos(2);

    public static void sleepNanos(long nanoDuration) throws InterruptedException {
        // see http://andy-malakov.blogspot.de/2010/06/alternative-to-threadsleep.html
        final long end = System.nanoTime() + nanoDuration;
        long timeLeft = nanoDuration;
        do {
            if (timeLeft > SLEEP_PRECISION)
                Thread.sleep(1);
            else
                Thread.yield();
            timeLeft = end - System.nanoTime();
            if (Thread.interrupted())
                throw new InterruptedException();
        } while (timeLeft > 0);
    }
}

Related

  1. sleep(long durationMillis)
  2. sleep(long millis)
  3. sleep(long milliseconds)
  4. sleepForSeconds(int seconds)
  5. sleepMilliseconds(long milliseconds)
  6. sleepNanos(long nanoDuration)
  7. sleepQuietly(int seconds)
  8. sleepSeconds(int secs)
  9. string2Millis(String duration)