import javax.swing.*;
class First{
public static void main(String args[]){
// Creating threads
Thread t1 = new Thread(new Second("first"));
Thread t2 = new Thread(new Second("second"));
Thread t3 = new Thread(new Second("third"));
Thread t4 = new Thread(new Second("fourth"));
// Starting the threads
t1.start();
t2.start();
t3.start();
t4.start();
}
}
import java.util.Random;
public class Second implements Runnable{
String name;
int time;
Random r = new Random();
public Second(String x){
name = x;
// Picking a random number from 1 to 999
time = r.nextInt(999);
}
// Using the run() method that comes with the Runnable library
public void run(){
try{
// Putting the thread to sleep for a random amount of time
System.out.printf("%s is sleeping for %d\n", name, time);
Thread.sleep(time);
// When the thread wakes up it will print out this
System.out.printf("%s has woken up\n",name);
// Exception handling
}catch(Exception e){
System.out.println("Error!");
}
}
}