1. Random產(chǎn)生
這里示例,我們產(chǎn)生20個1000以內(nèi)的整數(shù)
import java.util.Random;
public class RandomTest {
public static void random1(){
Random r = new Random();
for(int i=0;i<20;i++){
int num = r.nextInt(1000);
System.out.print(num + " ");
}
}
public static void main(String[] args) {
random1();
}
}
//輸出
383 205 604 568 525 418 759 558 804 728 205 723 866 567 521 592 399 434 221 68
注:
1)這里的nextInt產(chǎn)生的數(shù),包括[0,num),也就是這里是0-999
2)Random初始化的時候,默認(rèn)是沒有參數(shù)的,也就是以當(dāng)前時間為種子,
而當(dāng)然我們也可以指定一個long的參數(shù)作為種子,
3)如果種子相同,產(chǎn)生的隨機數(shù)序列也是相同的
2. 使用Math.random產(chǎn)生
產(chǎn)生一個指定范圍的隨機數(shù)
public static void random2(){
int min = 1;
int max = 100;
for(int i=0;i<20;i++){
double d = Math.random();
int v = (int)(d * (max-min) + min);
System.out.print(v + " ");
}
System.out.println();
}
//輸出
74 88 65 13 34 72 13 14 13 75 62 92 9 73 45 47 16 64 74 52
注:
1)Math.random會產(chǎn)生一個[0.0-1.0)之間的隨機數(shù)
2)(int)(d(max-min) + min) 產(chǎn)生[min,max)之間的數(shù),d(max-min)產(chǎn)生[0,(max-min)),
d*(max-min) +min產(chǎn)生[min,max)之間的隨機數(shù)
3. ThreadLocalRandom產(chǎn)生
public static void random3(){
for(int i=0;i<20;i++){
int num = ThreadLocalRandom.current().nextInt(1000);
System.out.print(num + " ");
}
System.out.println();
}
//輸出
585 971 182 919 416 505 127 223 662 944 533 340 990 763 738 863 566 970 645 996
使用方法類似于第一種
4. 使用SecureRandom產(chǎn)生
使用加密的強隨機數(shù)生成器RNG,使產(chǎn)生的種子是真正的隨機數(shù),保證輸出的不確定性
public static void random4() throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
for(int i=0;i<20;i++){
int num = random.nextInt(1000);
System.out.print(num + " ");
}
}
//輸出
788 72 159 367 254 9 157 681 367 8 636 34 695 202 530 960 832 489 439 215