Using isAlive() and join() with threads

The following example illustrates the use of isAlive() and join() methods.

class MyThread extends Thread
{
public MyThread()
{
// Set a name to child thread
setName("My Thread");
// Start the thread
start();
}
public void run()
{
try
{
for(int i=5;i>=1;i--)
{
System.out.println(getName()+": "+i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println("My thread interrupted.");
}
}
}
class isAliveAndJoinDemo
{
public static void main(String args[])
{
// Get current thread's object
Thread mainThread=Thread.currentThread();
// Set a name to main thread
mainThread.setName("Main Thread");
// Create child thread object
MyThread m=new MyThread();
// Start the loop
try
{
for(int i=5;i>=1;i--)
{
System.out.println(mainThread.getName()+": "+i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println("Main thread interrupted.");
}
// Print whether My thread is alive or not
if(m.isAlive())
System.out.println("My Thread is alive");
else
System.out.println("My Thread is dead");
// Wait for this thread to end
try
{
m.join();
}catch(InterruptedException e){
System.out.println("Interrupted while join");
}
// Print whether My thread is alive or not (After join)
if(m.isAlive())
System.out.println("My Thread is alive");
else
System.out.println("My Thread is dead");
}
}
----------------------------------------------
Output :
----------------------------------------------

Main Thread: 5
My Thread: 5
Main Thread: 4
My Thread: 4
My Thread: 3
Main Thread: 3
My Thread: 2
Main Thread: 2
My Thread: 1
Main Thread: 1
My Thread is alive
My Thread is dead



Posted by at on

Tags: Multi Threading,