Java堆与栈内存分配及String小记(5)

顺便学习了下Random函数:

参考jdk源码,带参构造函数是由一个种子的,根据种子来确定随机数
public Random(long seed) {
this.seed = new AtomicLong(0L);
setSeed(seed);
}
无参构造函数,是直接使用当前时间来作为种子
public Random() { this(++seedUniquifier + System.nanoTime()); }

参考nextInt源代码
public int nextInt(int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");

if ((n & -n) == n)  // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);

int bits, val;
do {
bits = next(31);
val = bits % n;
} while (bits - val + (n-1) < 0);
return val;
}

protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwpdxs.html