Pacific-Design.com

    
Home Index

1. Java

2. ThreadLocalRandom

Java / ThreadLocalRandom /

package threadlocalrandom;

import java.util.concurrent.ThreadLocalRandom;

public class Main {

    public static void main(String args[]) throws InterruptedException {

        // Creating 5 threads
        for (int i = 0; i < 5; i++) {
            final Thread thread = new Thread() {

                @Override
                public void run() {
                    System.out.print(Thread.currentThread().getName() + "\t");

                    // Generating 10 random numbers - random for every thread
                    for (int j = 0; j < 10; j++) {
                        final int random = ThreadLocalRandom.current().nextInt(0, 10);
                        System.out.print(random + ",");
                    }
                    System.out.println();
                }
            };
            thread.start();
            thread.join();
        }
    }
}


run:
Thread-0    6,8,9,9,1,0,1,3,7,6,
Thread-1    2,3,6,9,3,6,1,4,8,4,
Thread-2    8,9,8,2,4,5,9,4,9,6,
Thread-3    3,1,3,0,9,3,3,1,7,5,
Thread-4    0,9,5,7,0,3,8,7,3,5,