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.

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