Languages
[Edit]
EN

Java - random int number in both inclusive range with threads

4 points
Created by:
Tehya-Blanchard
444

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 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join