Checking the thread’s life (isAlive())



To check whether a particular thread is in live state or not, at any time we use isAlive() method. This method returns true if the thread for which it called is in the living state and it returns false if the thread is not alive.
//isAlive 
class MyThread extends Thread
{
    public void run()
    {
        for(int i=0;i<10;i++)
        {    
            try
            {
                sleep(500);
            }catch(InterruptedException e){}
        }
    } 
}
class MyThreadTest
{
    public static void main(String ar[])
    {
        System.out.println("Start main");
        MyThread t1=new MyThread();
        t1.start();
        for(int i=0;i<12;i++)
        {    
            try
            {
                Thread.sleep(1000);
            }catch(InterruptedException e){}
            if(t1.isAlive())
                System.out.println("t1 is Alive");
            else
                System.out.println("t1 is not alive");
        }
        System.out.println("Exit from main");
    }
}
/*OUTPUT
Start main
t1 is Alive
t1 is Alive
t1 is Alive
t1 is Alive
t1 is Alive
t1 is not alive
t1 is not alive
t1 is not alive
t1 is not alive
 Exit from main
*/

No comments:

Popular Posts