Java tutorial
//package com.java2s; //License from project: Apache License public class Main { /** Sleeps between floor and ceiling milliseconds, chosen randomly */ public static void sleepRandom(long floor, long ceiling) { if (ceiling - floor <= 0) { return; } long diff = ceiling - floor; long r = (int) ((Math.random() * 100000) % diff) + floor; sleep(r); } /** Returns a random value in the range [1 - range] */ public static long random(long range) { return (long) ((Math.random() * range) % range) + 1; } /** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */ public static void sleep(long timeout) { try { Thread.sleep(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } public static void sleep(long timeout, int nanos) { //the Thread.sleep method is not precise at all regarding nanos if (timeout > 0 || nanos > 900000) { try { Thread.sleep(timeout + (nanos / 1000000), (nanos % 1000000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } else { //this isn't a superb metronome either, but allows a granularity //with a reasonable precision in the order of 50ths of millisecond long initialTime = System.nanoTime() - 200; while (System.nanoTime() < initialTime + nanos) ; } } }