Generate random numbers using ThreadLocalRandom class

Random numbers are always only pseudo-random numbers and are generated with a mathematical formula from the predecessor. The predecessor must be stored, which is the task of a random object. The method Math.random() uses internally a random object, whereby it can come to waiting periods, if several threads call random() at the same time.

To be able to generate random numbers quickly, these delays are unfavorable. The class java.util.concurrent.ThreadLocalRandom is a subclass of the Random class and overrides the actual random number generator method. Accordingly, generating random numbers via the ThreadLocalRandom class is faster than the Math.random() method.

The program starts by importing the java.util.concurrent.ThreadLocalRandom class. Then, the main method is declared.

Within the main method, three random numbers are generated: one integer, one double, and one boolean. The nextInt method is called on the ThreadLocalRandom class to generate the integer. The nextDouble method is called to generate the double and the nextBoolean method is called to generate the boolean value.

Finally, the values of the random numbers are printed to the console.

import java.util.concurrent.ThreadLocalRandom;

public class RandomNumbersExample {
    public static void main(String[] args) {
      int randomInteger = ThreadLocalRandom.current().nextInt();  
      double randomDouble = ThreadLocalRandom.current().nextDouble(); 
      boolean randomBoolean = ThreadLocalRandom.current().nextBoolean(); 
      System.out.println("random integer: " + randomInteger); 
      System.out.println("random double: " + randomDouble);       
      System.out.println("random boolean: " + randomBoolean);
Output first run
random integer: 550355810
random double: 0.7748510999681417
random boolean: false
Output second run
random integer: -496196540
random double: 0.45972132487239736
random boolean: true