Thread class methods isAlive(), join()
class NewThread implements Runnable{
String name;
Thread t;
NewThread(String n){
name = n;
t = new Thread(this,name);
System.out.println("Child: "+t);
t.start();
}
public void run(){
try{
for(int i=5;i>0;i--){
System.out.println("Name: "+i);
Thread.sleep(1000);
}
} catch (InterruptedException e){
System.out.println("Thread "+name+" Interrupted");
}
System.out.println(name+" Exiting");
}
}
class AliveJoin {
public static void main(String[] args){
NewThread obj1 = new NewThread("One");
NewThread obj2 = new NewThread("Two");
NewThread obj3 = new NewThread("Three");
System.out.println("Thread One is Alive: "+obj1.t.isAlive());
System.out.println("Thread Two is Alive: "+obj2.t.isAlive());
System.out.println("Thread Three is Alive: "+obj3.t.isAlive());
try {
System.out.println("Waiting for Threads");
obj1.t.join();
obj2.t.join();
obj3.t.join();
} catch (InterruptedException e) {
System.out.println("Main Interrupted");
}
System.out.println("Thread One is Alive: "+obj1.t.isAlive());
System.out.println("Thread Two is Alive: "+obj2.t.isAlive());
System.out.println("Thread Three is Alive: "+obj3.t.isAlive());
}
}
No comments:
Post a Comment