![Random类UML图](https://i-blog.csdnimg.cn/blog_migrate/1e1003a243e2547a7f2b67166042b3c1.png)
由于计算机是一个确定的系统,它的操作是基于事先定义好的指令和算法的。因此计算机并不能真正生成随机数。伪随机数中的生成算法,利用了一个称为种子的初始值,通过一定的数学规则生成一个数列,此数列再统计学上表现出类似于真随机数的特征。
对于某些需要高度随机性和安全性的应用,如密码学,伪随机数可能不足以满足要求,这时需要使用更强大的随机数生成器,如硬件随机数生成器或加密学中的 SecureRandom 类。
Random特征
- 是伪随机数类,相同种子相同次序的数相同
- 有两个构造函数,一个无参,一个有种子参数的构造函
/**
* Creates a new random number generator. This constructor sets
* the seed of the random number generator to a value very likely
* to be distinct from any other invocation of this constructor.
* 创建一个新的随机数生成器。这个构造函数将随机数生成器的种子设置为一个值,该值很可能不同于这个构造函数的任何其他调用。
*/
public Random() {
this(seedUniquifier() ^ System.nanoTime());
}
/** * Creates a new random number generator using a single {@code long} seed.
* The seed is the initial value of the internal state of the pseudorandom * number generator which is maintained by method {@link #next}.
* * <p>The invocation {@code new Random(seed)} is equivalent to: * <pre> {@code * Random rnd = new Random(); * rnd.setSeed(seed);}</pre> * * @param seed the initial seed * @see #setSeed(long)
*/
public Random(long seed) {
if (getClass() == Random.class)
this.seed = new AtomicLong(initialScramble(seed));
else {
// subclass might have overriden setSeed 子类可能已经覆盖了setSeed
this.seed = new AtomicLong();
setSeed(seed);
}
}
synchronized public void setSeed(long seed) {
this.seed.set(initialScramble(seed));
haveNextNextGaussian = false;
}
Random源码https://github.com/WRJcode/HelloWorld/blob/main/src/java/util/Random.java