EN
Java - random int number in both inclusive range with threads
4 points
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:
xxxxxxxxxx
1
import java.util.concurrent.ThreadLocalRandom;
2
3
public class ThreadRandomUtil {
4
5
public static int generateInclusiveInteger(int min, int max) {
6
ThreadLocalRandom randomizer = ThreadLocalRandom.current();
7
8
return min + randomizer.nextInt((max - min) + 1);
9
}
10
}
Usage example:
xxxxxxxxxx
1
import java.util.Random;
2
3
public class Program {
4
5
public static void main(String[] args) {
6
7
// Now we can use ThreadRandomUtil.generateInclusiveInteger(1, 3) inside any thread.
8
// In below usage example we use only main thread.
9
10
for (int i = 0; i < 5; i++) {
11
int randomNumber = ThreadRandomUtil.generateInclusiveInteger(1, 3);
12
13
System.out.println(randomNumber);
14
}
15
}
16
}
Output:
xxxxxxxxxx
1
1
2
3
3
2
4
1
5
2
Note:
ThreadLocalRandom.current()
returnsThreadLocalRandom
object for current thread.