Java ThreadLocalRandom generate concurrent random numbers

Description

Java ThreadLocalRandom generate concurrent random numbers


import java.util.concurrent.ThreadLocalRandom;

class TaskLocalRandom implements Runnable {

  public TaskLocalRandom() {
    ThreadLocalRandom.current();//from w w w. j a  v a2s.  c  o m
  }

  @Override
  public void run() {
    String name = Thread.currentThread().getName();
    for (int i = 0; i < 10; i++) {
      System.out.printf("%s: %d\n", name, ThreadLocalRandom.current().nextInt(10));
    }
  }

}

public class Main {
  public static void main(String[] args) {
    Thread threads[] = new Thread[3];
    for (int i = 0; i < threads.length; i++) {
      TaskLocalRandom task = new TaskLocalRandom();
      threads[i] = new Thread(task);
      threads[i].start();
    }
  }
}



PreviousNext

Related