I was trying a example of isAlive()
method of java threading. But i found that isAlive()
method is returning false
even if thread has been already started. Can someone please tell me what am i doing wrong? Here is the code snippet.
package app;
public class ThreadAliveDemo {
public static void main(String[] args) {
Thread myThread;
myThread = new Thread()
{
public void run()
{
Thread.sleep(3000);
System.out.println("My Thread.");
}
};
myThread.setName("My Thread");
myThread.start();
if(!myThread.isAlive())
{
myThread.setName("My Thread");
myThread.start();
}
}
}
Java Thread isAlive() methodThe isAlive() method of thread class tests if the thread is alive. A thread is considered alive when the start() method of thread class has been called and the thread is not yet dead. This method returns true if the thread is still running and not finished.
The isAlive function − It is used to check if a thread is alive or not. Alive refers to a thread that has begun but not been terminated yet. When the run method is called, the thread operates for a specific period of time after which it stops executing.
This method is used to find out if a thread has actually been started and has yet not terminated. Note: While returning this function returns true if the thread upon which it is called is still running. It returns false otherwise.
In java, isAlive() and join() are two different methods that are used to check whether a thread has finished its execution or not. The isAlive() method returns true if the thread upon which it is called is still running otherwise it returns false. But, join() method is used more commonly than isAlive().
There's a good chance the thread will have started, executed, and finished, between your call to start()
and your call to isAlive()
.
Java offers no guarantees on the sequence in which these things happen. It could execute the spawned thread immediately, or it may choose to defer it until a bit later.
Incidentally, your code is trying to re-start the thread after it has died. This is not permitted:
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
So calling start()
after checking isAlive()
is never going to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With