Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isAlive() method of java thread is not working properly?

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();
        }

    }

}
like image 205
Rise Avatar asked Jun 29 '10 12:06

Rise


People also ask

How use isAlive method in Java?

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.

How does thread isAlive work?

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.

What is the return type of isAlive () method in Java?

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.

What is use of isAlive () and join () methods?

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().


1 Answers

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.

like image 177
skaffman Avatar answered Sep 18 '22 10:09

skaffman