Follow these steps to implement the example:
- Create a class named TaskLocalRandom and specify that it implements the Runnable interface:
public class TaskLocalRandom implements Runnable {
- Implement the run() method. Get the name of the thread that is executing this task and write 10 random integer numbers to the console using the nextInt() method:
@Override
public void run() {
String name=Thread.currentThread().getName();
for (int i=0; i<10; i++){
System.out.printf("%s: %d ",name,
ThreadLocalRandom.current().nextInt(10));
}
}
- Implement the main class of the example by creating a class named Main and add the main() method to it:
public class Main {
public static void main(String[] args) {
- Create an array for three Thread objects:
Thread threads[]=new Thread[3];
- Create and launch three TaskLocalRandom tasks. Store the threads in the array created earlier:
for (int i=0; i<3; i++) {
TaskLocalRandom task=new TaskLocalRandom();
threads[i]=new Thread(task);
threads[i].start();
}