Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...