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
278 views
in Technique[技术] by (71.8m points)

java - Who notifies the Thread when it finishes?

I have one question regarding wait/notify based threads interaction.

The output of the below code is Im. How output can be Im as there is no other thread calling notify() on Thread object. Is it like JVM implicitly calls notify() in above such scenarios where you try to wait on Thread class instance.

A thread operation gets stuck when it waits without receiving any notification. Now what if I wait on Thread class instance wait(). For e.g.

public class WaitingThread {
    public static void main(String[] args) {
        Thread t1 = new Thread();
        t1.start();
        synchronized (t1) {
            try {
                t1.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Im");
    }
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Your program is leaving wait() because the thread is finishing immediately. This is a byproduct of the Thread library that the Thread object is notified when the thread finishes. This is how join() works but it is not behavior that should be relied on since it is internal to the thread sub-system.

If you are trying to wait for the thread to finish then you should be using the t1.join() method instead.

Your thread is finishing immediately because it does not have a run() method defined so it is started and finishes. Really it is a race condition and the thread that is started could finish before the main thread gets to the wait() method call. You can see this if you put a short sleep (maybe 10ms) after the start() is called. Then you can see that you program will sit in wait() forever.


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

...