new Random()
1.以這種形式實例化對象時蒋情,Java編譯器以系統(tǒng)當(dāng)前時間作為隨機數(shù)生成器的種子,因為每時每刻的時間都不可能相同皂甘,所以產(chǎn)生的隨機數(shù)也不同佳魔。如果運行速度太快,也會產(chǎn)生兩次運行結(jié)果相同的隨機數(shù)罚屋。
2.偽隨機既有規(guī)則的隨機苦囱,Random類中的隨機算法就是偽隨機。具體表現(xiàn)為:相同種子數(shù)的Random對象生成的隨機數(shù)序列相同:
Random r1 = new Random(100);
Random r2 = new Random(100);
結(jié)果:產(chǎn)生的隨機數(shù)相同脾猛。
3.產(chǎn)生 1~50的整數(shù)
n + (new Random()).nextInt(m-n+1)
例:
生成整數(shù)隨機數(shù)
Random rand=new Random();
for(inti= 0;i< 50;i++) {
try{
Thread.sleep(500);
}catch(InterruptedException e) {
//TODOAuto-generated catch block
e.printStackTrace();
}
int num = rand.nextInt(3) +1;
System.out.println(num);
//返回大于等于m小于m+n(不包括m+n)之間的隨機數(shù)
int num2= m + (int)(Math.random() * n);
System.out.println("======="+num2);
int num3=(int)(Math.random() * n);//返回大于等于0小于n之間的隨機數(shù)
}
生成double的隨機數(shù)
Random rand=new Random();
for(inti= 0;i< 50;i++) {
try{
Thread.sleep(800);
}catch(InterruptedExceptione) {
//TODOAuto-generated catch block
e.printStackTrace();
}
doublenum=rand.nextDouble()* 0.05 + 0.01;
System.out.println(num);
//返回大于等于m小于m+n(不包括m+n)之間的隨機數(shù)
doublenum2= 0.01+ (double)(Math.random() * 0.05);
System.out.println("======="+num2);
intnum3=(int)(Math.random() * 0.05);//返回大于等于0小于n之間的隨機數(shù)
System.out.println("==="+num3);
}
Math.random() 方法生成[0, 1)范圍內(nèi)的double類型隨機數(shù)撕彤;Random類中的nextXxxx系列方法生成0-n的隨機數(shù);
Math.random() 線程安全猛拴,多線程環(huán)境能被調(diào)用羹铅;
如無特殊需求,則使用(int)(Math.random()*n)的方式生成隨機數(shù)即可愉昆。