最近对随即函数调用时有些奇怪的问题,想请教大家:
public class IDGenerate {
public static void main(String[] args){
for(int i=0;i<5;i++){
Random rnd = new Random();
int r=rnd.nextInt()>=0?rnd.nextInt():-rnd.nextInt();
System.out.println(r);
}
}
}
这个函数输出的5个随即数相同,为什么呢?
public class IDGenerate {
public static void main(String[] args){
for(int i=0;i<5;i++){
Random rnd = new Random();
int r=rnd.nextInt()>=0?rnd.nextInt():-rnd.nextInt();
System.out.println(r);
}
}
}
这个函数输出的5个随即数相同,为什么呢?
2098450842
-982831940
-1772027138
1509088062-1670545072
-2063912227
-890722475
-2009416296
-1373439530测试的结果如上
楼主自己运行一下,程序没有问题
还有最好在
Random rnd = new Random();
这个创建对象语句写在for循环外面 , 这样写的程序效率高一点!
这个创建对象语句写在for循环外面 就产生不一样的数字 放在里面就是一样的 为什么啊?
没有指定种子就使用System.currentTimeMillis()
因为程序很快,在循环中每次获得的时间戳一样,所以产生的随机数是一样的(这样才是正确的)
当然如果你的CPU比较慢,或者你多重复几次,你会看到后面的随机数是不一样的!
使用java.security.SecureRandom试试