ThreadLocalRandom Concurrent Draws
Draw bounded random numbers without a shared seed using ThreadLocalRandom.current(), so concurrent tasks never contend on one Random instance.
Code
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
public class DiceRoller {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(4);
// 每个任务在自己的线程里调 ThreadLocalRandom.current():
// 各拿各的内部实例,并发任务之间不竞争共享种子
for (int task = 1; task <= 4; task++) {
int id = task;
pool.submit(() -> {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
for (int i = 0; i < 3; i++) {
int roll = rnd.nextInt(1, 7); // 含头不含尾:[1, 7) 即骰子 1..6
System.out.println("task " + id + " roll: " + roll);
}
System.out.println("task " + id + " uniform: " + rnd.nextDouble(-1.0, 1.0));
});
}
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS); // 等全部并发任务跑完
}
}Inside the snippet
ThreadLocalRandom Concurrent Draws reduces to the class DiceRoller.
Iteration happens inside for (int task = 1; task <= 4; task++) — everything outside it runs once.
Using it
The demo output is labeled (task); each label names the call that printed it.
Key statements
ExecutorService pool = Executors.newFixedThreadPool(4);
ThreadLocalRandom rnd = ThreadLocalRandom.current();
Interactive Tools for This Topic
Passphrase GeneratorGenerate memorable multi-word passphrases from a fixed 150-word list with crypto randomness, separators, and capitalization options.Password GeneratorGenerate random passwords from selectable character classes using crypto.getRandomValues with rejection sampling and class guarantees.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.UUID v4 GeneratorGenerate cryptographically random UUIDs version 4 using the Web Crypto API. Produce single or batch UUIDs with optional uppercase formatting and copy-to-clipboard support.
FAQ
- What does ThreadLocalRandom Concurrent Draws print when run?
- No setup needed: run the file and look for labeled lines like `task` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.