本文共 3627 字,大约阅读时间需要 12 分钟。
该类的实例用于生成伪随机数。该类使用原值为48位的种子,其使用线性同余公式进行修改。如果使用相同的种子创建两个Random,并且对每个实例进行相同的方法调用该序列,则它们将生成并返回相同的数字序列。通过调用私有方法next(int bits)方法可以提供多达32个伪随机生成位。java.util.Random是线程安全的。 但是,跨线程的同时使用java.util.Random实例可能会遇到争用,从而导致性能下降。但java.util.Random并不是加密安全的。
public class Random implements java.io.Serializable { //使用JDK 1.1中的serialVersionUID实现互操作性 static final long serialVersionUID = 3905348978240129619L; //与这个伪随机数生成器相关联的内部状态。 private final AtomicLong seed; private static final long multiplier = 0x5DEECE66DL; private static final long addend = 0xBL; private static final long mask = (1L << 48) - 1; private static final double DOUBLE_UNIT = 0x1.0p-53; // 异常信息 static final String BadBound = "bound must be positive"; static final String BadRange = "bound must be greater than origin"; static final String BadSize = "size must be non-negative";}
public Random() { this(seedUniquifier() ^ System.nanoTime()); } public Random(long seed) { if (getClass() == Random.class) this.seed = new AtomicLong(initialScramble(seed)); else { this.seed = new AtomicLong(); setSeed(seed); } }
public void nextBytes(byte[] bytes) { for (int i = 0, len = bytes.length; i < len; ) for (int rnd = nextInt(), n = Math.min(len - i, Integer.SIZE/Byte.SIZE); n-- > 0; rnd >>= Byte.SIZE) bytes[i++] = (byte)rnd; }
public int nextInt() { return next(32); } public int nextInt(int bound) { if (bound <= 0) throw new IllegalArgumentException(BadBound); int r = next(31); int m = bound - 1; if ((bound & m) == 0) // i.e., bound is a power of 2 r = (int)((bound * (long)r) >> 31); else { for (int u = r; u - (r = u % bound) + m < 0; u = next(31)) ; } return r;}
public long nextLong() { // it's okay that the bottom word remains signed. return ((long)(next(32)) << 32) + next(32); }
public boolean nextBoolean() { return next(1) != 0; }
public float nextFloat() { return next(24) / ((float)(1 << 24)); }
public double nextDouble() { return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT; }
synchronized public double nextGaussian() { // See Knuth, ACP, Section 3.4.1 Algorithm C. if (haveNextNextGaussian) { haveNextNextGaussian = false; return nextNextGaussian; } else { double v1, v2, s; do { v1 = 2 * nextDouble() - 1; // between -1 and 1 v2 = 2 * nextDouble() - 1; // between -1 and 1 s = v1 * v1 + v2 * v2; } while (s >= 1 || s == 0); double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); nextNextGaussian = v2 * multiplier; haveNextNextGaussian = true; return v1 * multiplier; } }
转载地址:http://jhao.baihongyu.com/