Languages
[Edit]
EN

Java - random int number in both inclusive range with threads

4 points
Created by:
Kate_C
19800

In this short article we would like to show how to generate both inclusive random numbers in a range inside threads using Java. We want to generate numbers using built-in Java API.

Motivation to use below solution is better performance than just Random class when we work with many threads. ThreadLocalRandom provides separated randomizers related with specific thread that generate numbers in independent way.

Quick solution:

import java.util.concurrent.ThreadLocalRandom;

public class ThreadRandomUtil {

    public static int generateInclusiveInteger(int min, int max) {
        ThreadLocalRandom randomizer = ThreadLocalRandom.current();

        return min + randomizer.nextInt((max - min) + 1);
    }
}

Usage example:

import java.util.Random;

public class Program {

    public static void main(String[] args) {

        // Now we can use ThreadRandomUtil.generateInclusiveInteger(1, 3) inside any thread.
        // In below usage example we use only main thread.

        for (int i = 0; i < 5; i++) {
            int randomNumber = ThreadRandomUtil.generateInclusiveInteger(1, 3);
            
            System.out.println(randomNumber);
        }
    }
}

Output:

1
3
2
1
2

Note: ThreadLocalRandom.current() returns ThreadLocalRandom object for current thread.

References

  1. Class ThreadLocalRandom - Oracle Docs 

Native Advertising
50 000 ad impressions - 449$
ūüöÄ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

‚̧ԳŹūüíĽ ūüôā

Join