Java 生成隨機數(shù)的 5 種方式,你知道幾種?
閱讀本文大概需要 5.5 分鐘。
作者:專職跑龍?zhí)?/span>
鏈接:https://www.jianshu.com/p/2f6acd169202
1. Math.random() 靜態(tài)方法
double,即?0 <= random <= 1。for?(int?i?=?0;?i?10;?i++)?{
??System.out.println(Math.random());
}
0.3598613895606426 0.2666778145365811 0.25090731064243355 0.011064998061666276 0.600686228175639 0.9084006027629496 0.12700524654847833 0.6084605849069343 0.7290804782514261 0.9923831908303121
When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random() This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.
Math.random()?方法時,自動創(chuàng)建了一個偽隨機數(shù)生成器,實際上用的是?new java.util.Random()。當(dāng)接下來繼續(xù)調(diào)用?Math.random()?方法時,就會使用這個新的偽隨機數(shù)生成器。public?static?double?random()?{
????Random?rnd?=?randomNumberGenerator;
????if?(rnd?==?null)?rnd?=?initRNG();?//?第一次調(diào)用,創(chuàng)建一個偽隨機數(shù)生成器
????return?rnd.nextDouble();
}
private?static?synchronized?Random?initRNG()?{
????Random?rnd?=?randomNumberGenerator;
????return?(rnd?==?null)???(randomNumberGenerator?=?new?Random())?:?rnd;?//?實際上用的是new?java.util.Random()
}
This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.
initRNG()?方法是?synchronized?的,因此在多線程情況下,只有一個線程會負(fù)責(zé)創(chuàng)建偽隨機數(shù)生成器(使用當(dāng)前時間作為種子),其他線程則利用該偽隨機數(shù)生成器產(chǎn)生隨機數(shù)。Math.random()?方法是線程安全的。線程1在第一次調(diào)用? random()?時產(chǎn)生一個生成器?generator1,使用當(dāng)前時間作為種子。線程2在第一次調(diào)用? random()?時產(chǎn)生一個生成器?generator2,使用當(dāng)前時間作為種子。碰巧? generator1?和?generator2?使用相同的種子,導(dǎo)致?generator1以后產(chǎn)生的隨機數(shù)每次都和?generator2?以后產(chǎn)生的隨機數(shù)相同。
Math.random()?靜態(tài)方法使用線程1在第一次調(diào)用? random()?時產(chǎn)生一個生成器?generator1,使用當(dāng)前時間作為種子。線程2在第一次調(diào)用? random()?時發(fā)現(xiàn)已經(jīng)有一個生成器generator1,則直接使用生成器?generator1。
public?class?JavaRandom?{
????public?static?void?main(String?args[])?{
????????new?MyThread().start();
????????new?MyThread().start();
????}
}
class?MyThread?extends?Thread?{
????public?void?run()?{
????????for?(int?i?=?0;?i?2;?i++)?{
????????????System.out.println(Thread.currentThread().getName()?+?":?"?+?Math.random());
????????}
????}
}
Thread-1: 0.8043581595645333 Thread-0: 0.9338269554390357 Thread-1: 0.5571569413128877 Thread-0: 0.37484586843392464
2. java.util.Random 工具類
An attacker will simply compute the seed from the output values observed. This takes?significantly less?time than 2^48 in the case of java.util.Random. 從輸出中可以很容易計算出種子值。It is shown that you can predict future Random outputs observing only two(!) output values in time roughly 2^16. 因此可以預(yù)測出下一個輸出的隨機數(shù)。You should never use an LCG for security-critical purposes.在注重信息安全的應(yīng)用中,不要使用 LCG 算法生成隨機數(shù),請使用 SecureRandom。
Random?random?=?new?Random();
for?(int?i?=?0;?i?5;?i++)?{
????System.out.println(random.nextInt());
}
-24520987 -96094681 -952622427 300260419 1489256498
public?Random()?{
????this(seedUniquifier()?^?System.nanoTime());
}
public?Random(long?seed)?{
????if?(getClass()?==?Random.class)
????????this.seed?=?new?AtomicLong(initialScramble(seed));
????else?{
????????//?subclass?might?have?overriden?setSeed
????????this.seed?=?new?AtomicLong();
????????setSeed(seed);
????}
}
nextBoolean()?- 返回均勻分布的?true?或者?falsenextBytes(byte[] bytes)nextDouble()?- 返回 0.0 到 1.0 之間的均勻分布的?doublenextFloat()?- 返回 0.0 到 1.0 之間的均勻分布的?floatnextGaussian()- 返回 0.0 到 1.0 之間的高斯分布(即正態(tài)分布)的?doublenextInt()?- 返回均勻分布的?intnextInt(int n)?- 返回 0 到 n 之間的均勻分布的?int?(包括 0,不包括 n)nextLong()?- 返回均勻分布的?longsetSeed(long seed)?- 設(shè)置種子
Random?random1?=?new?Random(10000);
Random?random2?=?new?Random(10000);
for?(int?i?=?0;?i?5;?i++)?{
????System.out.println(random1.nextInt()?+?"?=?"?+?random2.nextInt());
}
-498702880 = -498702880 -858606152 = -858606152 1942818232 = 1942818232 -1044940345 = -1044940345 1588429001 = 1588429001
3. java.util.concurrent.ThreadLocalRandom 工具類
ThreadLocalRandom?是 JDK 7 之后提供,也是繼承至 java.util.Random。private?static?final?ThreadLocal
?localRandom?=
????new?ThreadLocal()?{
????????protected?ThreadLocalRandom?initialValue()?{
????????????return?new?ThreadLocalRandom();
????????}
};
ThreadLocalRandom?不是直接用?new?實例化,而是第一次使用其靜態(tài)方法?current()?得到?ThreadLocal?實例,然后調(diào)用?java.util.Random?類提供的方法獲得各種隨機數(shù)。public?class?JavaRandom?{
????public?static?void?main(String?args[])?{
????????new?MyThread().start();
????????new?MyThread().start();
????}
}
class?MyThread?extends?Thread?{
????public?void?run()?{
????????for?(int?i?=?0;?i?2;?i++)?{
????????????System.out.println(Thread.currentThread().getName()?+?":?"?+?ThreadLocalRandom.current().nextDouble());
????????}
????}
}
Thread-0: 0.13267085355389086 Thread-1: 0.1138484950410098 Thread-0: 0.17187774671469858 Thread-1: 0.9305225910262372
4. java.Security.SecureRandom
Instances of java.util.Random are not cryptographically secure.Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.SecureRandom?takes Random Data from your os (they can be interval between keystrokes etc - most os collect these data store them in files - /dev/random and /dev/urandom in case of linux/solaris) and uses that as the seed. 操作系統(tǒng)收集了一些隨機事件,比如鼠標(biāo)點擊,鍵盤點擊等等,SecureRandom 使用這些隨機事件作為種子。
SecureRandom?提供加密的強隨機數(shù)生成器 (RNG),要求種子必須是不可預(yù)知的,產(chǎn)生非確定性輸出。SecureRandom?也提供了與實現(xiàn)無關(guān)的算法,因此,調(diào)用方(應(yīng)用程序代碼)會請求特定的 RNG 算法并將它傳回到該算法的?SecureRandom?對象中。如果僅指定算法名稱,如下所示: SecureRandom random = SecureRandom.getInstance("SHA1PRNG");如果既指定了算法名稱又指定了包提供程序,如下所示: SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
SecureRandom?random1?=?SecureRandom.getInstance("SHA1PRNG");
SecureRandom?random2?=?SecureRandom.getInstance("SHA1PRNG");
for?(int?i?=?0;?i?5;?i++)?{
????System.out.println(random1.nextInt()?+?"?!=?"?+?random2.nextInt());
}
704046703 != 2117229935 60819811 != 107252259 425075610 != -295395347 682299589 != -1637998900 -1147654329 != 1418666937
5. 隨機字符串
RandomStringUtils?類。Maven 依賴如下:<dependency>
????<groupId>commons-langgroupId>
????<artifactId>commons-langartifactId>
????<version>2.6version>
dependency>
public?class?RandomStringDemo?{
????public?static?void?main(String[]?args)?{
????????//?Creates?a?64?chars?length?random?string?of?number.
????????String?result?=?RandomStringUtils.random(64,?false,?true);
????????System.out.println("random?=?"?+?result);
????????//?Creates?a?64?chars?length?of?random?alphabetic?string.
????????result?=?RandomStringUtils.randomAlphabetic(64);
????????System.out.println("random?=?"?+?result);
????????//?Creates?a?32?chars?length?of?random?ascii?string.
????????result?=?RandomStringUtils.randomAscii(32);
????????System.out.println("random?=?"?+?result);
????????//?Creates?a?32?chars?length?of?string?from?the?defined?array?of
????????//?characters?including?numeric?and?alphabetic?characters.
????????result?=?RandomStringUtils.random(32,?0,?20,?true,?true,?"qw32rfHIJk9iQ8Ud7h0X".toCharArray());
????????System.out.println("random?=?"?+?result);
????}
}
RandomStringUtils?類的實現(xiàn)上也是依賴了?java.util.Random?工具類:
推薦閱讀:
27歲、47歲!國內(nèi)兩家知名企業(yè)同時傳出員工猝死
超級全面的 SpringBoot 注解介紹,每一個用途都應(yīng)該清晰
微信掃描二維碼,關(guān)注我的公眾號
朕已閱?

