制作安全PRNG(Marsaglia' XorShift)时遇到一些问题,理论上每次执行时生成的值系列必须相同。但这不是我的情况,也不知道为什么。我必须使用compareAndSet
作为线程安全。
提前感谢您的帮助。
package fr.umlv.conc;
import java.util.concurrent.atomic.AtomicLong;
public class RandomTest {
private AtomicLong z = new AtomicLong();
public RandomTest(long seed) {
if (seed == 0) {
throw new IllegalArgumentException("seed == 0");
}
this.z = new AtomicLong(seed);
}
public long next() {
// Marsaglia's XorShift
AtomicLong seed = this.z;
long oldseed, nextseed;
do {
oldseed = seed.get();
nextseed = xorShift(oldseed);
} while (!seed.compareAndSet(oldseed, nextseed));
return nextseed * 2685821657736338717L;
}
private long xorShift(long x) {
x ^= x >>> 12;
x ^= x << 25;
x ^= x >>> 27;
return x;
}
public static void main(String[] args) {
for(int i=0; i < 3; i++) {
Thread t = new Thread(() -> {
RandomTest rng = new RandomTest(1);
for(int j = 0; j < 5_000; j++) {
System.out.println(rng.next());
}
});
t.start();
}
}
}