ThreadLocalRandom
, the recommended and most modern class (from Java 7)
SecureRandom
, a cryptographically strong random number generator
Random
, the superclass of both ThreadLocalRandom
and SecureRandom
Math.random
, a static method which generates doubles evenly distributed between 0 (inclusive) and 1 (exclusive).
To generate a series of random numbers as a unit, you need to use a single object. Do not create a new object for each new random number.
When methods in these classes accept a lower and upper bound, the lower bound is inclusive and the upper bound is exclusive.
Example
import java.util.concurrent.ThreadLocalRandom; /** Generating random numbers with ThreadLocalRandom. In Effective Java, Joshua Bloch recommends ThreadLocalRandom for most use cases (even for single-threaded code). @since Java 7. */ public final class RandomNumbers { public static final void main(String... args){ RandomNumbers prng = new RandomNumbers(); prng.zeroToUpperBound(100); prng.range(10, 21); prng.gaussian(100.0, 5.0); log("Done."); } /** The upper bound is excluded. */ void zeroToUpperBound(long upper){ log("Generating " + MAX + " random integers in the range 0.." + (upper-1)); //a single object is reused here ThreadLocalRandom generator = ThreadLocalRandom.current(); for (int idx = 1; idx <= MAX; ++idx){ long random = generator.nextLong(upper); log(INDENT + random); } } /** The lower bound is included, but the upper bound is excluded. */ void range(long lower, long upper){ log( "Generating " + MAX + " random integers in the range " + lower + ".." + (upper-1) ); //note the static factory method for getting an object; there's no constructor, //and there's no need to pass a seed ThreadLocalRandom generator = ThreadLocalRandom.current(); for (int idx = 1; idx <= MAX; ++idx){ long random = generator.nextLong(lower, upper); log(INDENT + random); } } void gaussian(double mean, double variance){ log("Generating " + MAX + " random doubles in a gaussian distribution."); log("Mean: " + mean + " Variance:" + variance); ThreadLocalRandom generator = ThreadLocalRandom.current(); for (int idx = 1; idx <= MAX; ++idx){ double random = mean + generator.nextGaussian() * variance; log(INDENT + random); } } //PRIVATE private static final int MAX = 10; private static final String INDENT = " "; private static void log(String aMessage){ System.out.println(aMessage); } }Example run of this class:
Generating 10 random integers in the range 0..99 4 71 31 88 95 69 94 24 36 39 Generating 10 random integers in the range 10..20 18 11 15 17 11 10 12 19 16 15 Generating 10 random doubles in a gaussian distribution. Mean: 100.0 Variance:5.0 96.29657359305843 99.72442335141267 103.91992986911049 96.53271254805549 101.20312372014465 102.12709319015893 103.7626473084215 102.47094971891569 100.86789127025881 101.78107900928805 Done.