2014年7月3日

Android: Nano Sleep

來源CALL GLOP()

private static final long SLEEP_PRECISION=2*1000000 ;
private static final long SPIN_YIELD_PRECISION= 1000;

    public static void sleepNanos (long nanoDuration) throws InterruptedException {
        final long end = System.nanoTime() + nanoDuration;
        long timeLeft = nanoDuration;
        do {
            if (timeLeft > SLEEP_PRECISION)
                Thread.sleep (1);
            else
                if (timeLeft > SPIN_YIELD_PRECISION)
                    Thread.sleep(0);

            timeLeft = end - System.nanoTime();
            if (Thread.interrupted())
                throw new InterruptedException ();
        } while (timeLeft > 0);
    }

沒有留言: