6 ways to generate random numbers in java
1. Introduction
This post would demo how to generate random integer numbers using java.
The ways include:
- Use the System.currentTimeInMillis to get [0,n)
- Use Math.random to get [0,n)
- Use Random to get [0,n)
- Use ThreadLocalRandom to get [0,n]
- Use Math.random to get [m,n]
- Use ThreadLocalRandom to get [m,n]
1. Environments
- Java 1.8
2. Example codes
2.1 Use the System.currentTimeInMillis to get [0,n)
This way would not generate a real random number, just the milli seconds of current time.
The test code:
we got the output:
2.2 Use Math.random to get [0,n)
The test code:
we got the output:
2.3 Use Random to get [0,n)
The test code:
we got the output:
2.4 Use ThreadLocalRandom to get [0,n]
The ThreadLocalRandom is provided since java 1.7, the javadoc
A random number generator isolated to the current thread. Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention. Use of ThreadLocalRandom is particularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers in parallel in thread pools.
The test code:
we got the output:
2.5 Use Math.random to get [m,n]
If you want to get a range of numbers,you can do like this:
The test code:
we got the output:
2.6 Use ThreadLocalRandom to get [m,n]
You can also ThreadLocalRandom to generate a range numbers.
The test code:
we got the output:
3. summary
In this post we demoed how to generate random numbers by using various methods.You can find the whole code examples on github project, the class source code is located at this
You can find detail documents about the java stream here: