ThreadLocalRandom Concurrent Draws

Draw bounded random numbers without a shared seed using ThreadLocalRandom.current(), so concurrent tasks never contend on one Random instance.

JavaData Integrity

Code

snippet
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

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.