ThreadLocalRandom
A ready random number generator that you do not need to create; fast in multithreaded code too.
Available since: Java 7
Syntax
public final class ThreadLocalRandom extends RandomExamples
Random numbers in ranges. The output differs on every run:
void main() {
var random = ThreadLocalRandom.current();
int dice = random.nextInt(1, 7);
double temp = random.nextDouble(-5.0, 30.0);
IO.println(dice);
IO.println(temp >= -5.0 && temp < 30.0);
}Output:
4
trueNotes
Always obtain it with ThreadLocalRandom.current() and do not store it in a shared field: each thread has its own generator. You cannot set a seed — for reproducible numbers use new Random(seed). The class is in the java.util.concurrent package.
See also
- Random — A random number generator: integers in a range, decimals, booleans.
- Math.random() — Returns a random decimal number from 0 (inclusive) to 1 (exclusive).
Related recipes
In the tutorial
- Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.