// 两种生成对象方式:带种子和不带种子(两种方式的区别见注解)
random random = new random();
integer res = random.nextint(n);
integer res = (int)(math.random() * n);
3、jdk源码
// random.nextint(n)
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;
}
// math.random()
public static double random() {
random rnd = randomnumbergenerator;
// 第一次调用,生成一个随机数生成器
if (rnd == null) rnd = initrng();
return rnd.nextdouble();
}
// 生成的方法为同步的,线程安全
private static synchronized random initrng() {
random rnd = randomnumbergenerator;
return (rnd == null) ? (randomnumbergenerator = new random()) : rnd;
}
// 该方法为 random 类中的方法
public double nextdouble() {
return (((long)(next(26)) << 27) + next(27))
/ (double)(1l << 53);
}
@test
public void createprojectno() {
random r1 = new random(100);
random r2 = new random(100);
for (int i = 0; i < 100; i ++) {
system.out.println(r1.nextint(10)+", "+r2.nextint(10));
}
}