Java Sleep sleepRandom(long timeout)

Here you can find the source of sleepRandom(long timeout)

Description

Sleeps between 1 and timeout milliseconds, chosen randomly.

License

LGPL

Declaration

public static void sleepRandom(long timeout) throws InterruptedException 
    

Method Source Code

//package com.java2s;

public class Main {
    /** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */
    public static void sleepRandom(long timeout) throws InterruptedException // GemStoneAddition
    {/*ww  w .jav a2s .c o m*/
        if (Thread.interrupted())
            throw new InterruptedException(); // GemStoneAddition
        if (timeout <= 0) {
            return;
        }

        long r = (int) ((Math.random() * 100000) % timeout) + 1;
        sleep(r);
    }

    /** Returns a random value in the range [1 - range] */
    public static long random(long range) {
        return (long) ((Math.random() * 100000) % range) + 1;
    }

    /** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */
    public static void sleep(long timeout) throws InterruptedException {
        //        try {
        Thread.sleep(timeout);
        //        }
        //        catch(Exception e) { // GemStoneAddition
        //        }
    }

    /**
     * On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will
     * sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the
     * thread never relinquishes control and therefore the sleep(x) is exactly x ms long.
     */
    public static void sleep(long msecs, boolean busy_sleep) throws InterruptedException // GemStoneAddition
    {
        if (Thread.interrupted())
            throw new InterruptedException(); // GemStoneAddition
        if (!busy_sleep) {
            sleep(msecs);
            return;
        }

        long start = System.currentTimeMillis();
        long stop = start + msecs;

        while (stop > start) {
            start = System.currentTimeMillis();
        }
    }
}

Related

  1. sleepQuietly(long millis)
  2. sleepQuietly(long ms)
  3. sleepQuite(long millis)
  4. sleepRandMs(int ms)
  5. sleepRandom(long floor, long ceiling)
  6. sleepSafely(final long millis)
  7. sleepSilently(int millis)
  8. sleepSilently(int millis)
  9. sleepThread(long millSecd)