/**
* Created by : Amar Ghugare
* created on : 21-05-2022 20:21
* Purpose of class : Write a program in java
* which will show lifecycle (creation, sleep, and dead)
* of a thread. Program should print randomly the name
* of thread and value of sleep time. The name of the
* thread should be hard coded through constructor.
* The sleep time of a thread will be a random integer
* in the range 0 to 4999.
*/
public class Slip12Q2 extends Thread {
public Slip12Q2(String s) {
super(s);
}
public void run() {
System.out.println(getName() + " thread created.");
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("THREAD NAME : "+this.getName()+"\n"+"THREAD PRIORITY : "+this.getPriority());
int s = (int) (Math.random() * 5000);
System.out.println(getName() + "is sleeping for : " + s + " mile sec");
try {
Thread.sleep(s);
} catch (Exception ignored) {
}
}
}
}
class ThreadLifeCycle{
public static void main(String[] args) {
Slip12Q2 t1=new Slip12Q2("Groot"),t2=new Slip12Q2("Amar");
t1.start();
t2.start();
try {
t1.join();
t2.join();
}
catch(Exception ignored) {}
System.out.println(t1.getName()+"thread dead.");
System.out.println(t2.getName()+"thread dead.");
}
}
No comments:
Post a Comment