Using isAlive() and join() with threads ~ foundjava
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: 5My Thread: 5Main Thread: 4My Thread: 4My Thread: 3Main Thread: 3My Thread: 2Main Thread: 2My Thread: 1Main Thread: 1My Thread is aliveMy Thread is dead
No comments:
Post a Comment