Java--Generate random numbers (Math.random() method, Random class, ThreadLocalRandom class, SecureRandom class)


1. The random() method of the Math class

Only random numbers of 0~1 (including 0, not including 1) of double type can be generated.

//产生一个min~max内的随机数。
int r = (int)min + (int)(Math.random() * (max - min));

2. Random class

The Random class is in the java.util package.

Create the object before using it:Random r = new Random();

Seed number : When generating random numbers, the source number of the random algorithm is called the seed number, and a certain transformation is performed on the basis of the seed number to generate the required random number.

The random algorithm used is the linear congruence method pseudo-random number ( LGC algorithm ).
 
Advantages :
 
It provides a wealth of random number generation methods, which can generate boolean, int, long, float, byte arrays and double types of random numbers
 
with high execution efficiency. Generates faster.
 
Disadvantages :
 
The random numbers generated are pseudo-random numbers, that is, regular random numbers.
 
When the objects have the same seed number, the random numbers generated by the same number of times are the same.

Two commonly used construction methods of Random :
 
1) Random(): This construction method uses the current system nanosecond time as the seed number, and then uses this seed number to construct a Random object.
 
2) Random(long seed): Create a new random number generator with a single parameter of type long.

Common methods of the Random class :

Random is thread safe.

Thread safety means that in a multi-threaded scenario, the execution result of the program is consistent with the expected result, which is called thread safety, otherwise it is not thread safe (also called thread safety). For example, if there are two threads, the first thread performs 100,000 ++ operations, and the second thread performs 100,000 - operations, then the final result should be neither added nor subtracted. If the final result of the program does not match expectations, It is not thread safe.


Three, ThreadLocalRandom class

Create a ThreadLocalRandom object before using it:
 
ThreadLocalRandom random = ThreadLocalRandom.current();

Advantages :
 
1) ThreadLocalRandom combines the Random and ThreadLocal classes and is isolated in the current thread. Therefore, it achieves better performance in a multi-threaded environment by avoiding competition for operating seeds, and it also ensures its thread safety.
 
2) Also, unlike Random, ThreadLocalRandom explicitly does not support setting random seeds. It overrides the
setSeed(long seed) method of Random and throws UnsupportedOperationException directly, thus reducing the possibility of repeated random numbers for multiple threads.

Disadvantage :
 
By default its random seed is also relative to the current time.
 
That is, if this parameter is not set by default, then in multi-threading, multiple threads can generate the same random number in each step of operation because of the same startup time.

Example :

//SecureRandom类的示例是仅将下面这一步改成:
// 创建 SecureRandom 对象,并设置加密算法
//SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

// 得到 ThreadLocalRandom 对象
ThreadLocalRandom random = ThreadLocalRandom.current();

for (int i = 0; i < 10; i++) {
    
    
    // 生成 0-9 随机整数
    int number = random.nextInt(10);
    // 打印结果
    System.out.println("生成随机数:" + number);
}

Fourth, the SecureRandom class

Create a SecureRandom object and set the encryption algorithm before use:
 
SecureRandom supports two encryption algorithms by default: SHA1PRNG algorithm and NativePRNG algorithm.
 
① SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
 
Or ② SecureRandom random = SecureRandom.getInstance("NativePRNG");
 
or use new SecureRandom()to create a SecureRandom object:
 
③SecureRandom secureRandom = new SecureRandom();
 
By default, the NativePRNG algorithm will be used to generate random numbers.

SecureRandom and Random
 
1) SecureRandom inherits from Random, which provides a cryptographically strong random number generator.
 
2) SecureRandom is different from Random, it collects some random events, such as mouse clicks, keyboard clicks, etc. SecureRandom uses these random events as seeds. That is, the seed is unpredictable, unlike Random which uses the milliseconds of the system's current time as the seed by default, thus avoiding the possibility of generating the same random number.


V. Summary

1) Math is an encapsulation of Random, the two are similar.
 
2) Random generates pseudo-random numbers with the current nanosecond time as the seed number.
 
When the multi-thread competition is fierce, there are certain performance problems to perform the CAS operation,
 
but for most application scenarios, using Random is enough.
 
3) When the multi-thread competition is fierce: Use ThreadLocalRandom instead of Random
 
4) When the security requirements are high: Use SecureRandom
 
because SecureRandom will collect some random events as random seeds, which can be regarded as a tool class for generating real random numbers.


reference:

C language Chinese network Java generates random numbers (random() and Random classes)

Cloud + Community - 4 ways to generate random numbers in Tencent Cloud Java! (⭐)

Guess you like

Origin blog.csdn.net/xiaoyu_alive/article/details/123322334