谁在线程结束时通知线程? [英] Who notifies the Thread when it finishes?

查看:138
本文介绍了谁在线程结束时通知线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于基于等待/通知的线程交互的问题。

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

以下代码的输出是 Im 。输出如何 Im 因为在Thread对象上没有其他线程调用 notify()。是否像JVM在上面尝试等待Thread类实例的情况下隐式调用 notify()

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.

线程操作在没有收到任何通知的情况下等待时会卡住。现在如果我等待Thread类实例 wait()。例如

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


推荐答案

您的程序正在离开 wait()因为线程正在立即完成。这是 Thread 库的副产品,当线程完成时会通知 Thread 对象。这就是 join()的工作方式,但它应该依赖 not 行为,因为它是线程子系统的内部。

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.

如果您正在尝试等待线程完成,那么您应该使用 t1.join()方法。

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

您的线程正在立即完成,因为它没有定义 run()方法,因此它已启动并且饰面。实际上它是一个竞争条件,并且启动的线程可以在主线程进入 wait()方法调用之前完成。如果在调用 start()后进行短暂睡眠(可能是10毫秒),您可以看到这一点。然后你可以看到你的程序将永远位于 wait()

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.

这篇关于谁在线程结束时通知线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆