如果在Thread上调用java wait(),则该方法也会在run()方法终止时退出 [英] if java wait() is called on a Thread, the method exits also on run() method termination

查看:232
本文介绍了如果在Thread上调用java wait(),则该方法也会在run()方法终止时退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对wait()方法的特定用例感到困惑。

根据javadoc,当出现下列情况之一时,wait应该结束:

I'm puzzled with a particular use case of the wait() method.
According with javadoc, wait should end when one of the following condition happens:


  • 另一个线程调用notify或notifyAll(好的,请参阅javadoc了解有关通知的详细信息,但这与此问题无关)

  • 另一个线程中断此(等待)线程

  • 超时到期(如果使用带超时的等待版本)

在我正在等待的对象本身就是一个Thread的情况下,即使没有调用notify(),并且没有上述任何一个条件成立,也会发生wait()退出。
但是当Thread.run()方法结束时会发生这种情况。
虽然这种行为可能有意义,但不应该在Thread javadoc中记录吗?
我发现它也很混乱,因为它与join()行为重叠。

In the case in which the object i'm waiting on is itself a Thread, it happens that the wait() exits even if no notify() has been called, and no one of the above conditions holds. But it happens when the Thread.run() method ends. While this behavior may make sense, shouldn't it be documented inside of Thread javadoc? I find it very confusing also because it overlaps with join() behavior.

这是我的测试代码:

public static class WorkerThread extends Thread {

    @Override public void run() {

        try{
           System.out.println("WT: waiting 4 seconds");
           Thread.sleep(4000);

           synchronized (this) {
            notify();
           }

           System.out.println("WT: waiting for 4 seconds again");
           Thread.sleep(4000);
           System.out.println("WT: exiting");

        } catch (InterruptedException ignore) {
            ignore.printStackTrace();
        }

    }

}

public static void main (String [] args) throws InterruptedException {

    WorkerThread w = new WorkerThread();

    w.start();

    synchronized(w) {
        w.wait();
        System.out.println("MT: The object has been notified by the thread!");
    }

    synchronized(w) {

        w.wait(); //THIS FINISHES WITHOUT notify(), interrupt() OR TIMEOUT!

        System.out.println("MT: The thread has been notified again!");
    }

}


推荐答案

自Java 7以来,在 join()方法的文档

It is documented since Java 7, in the documentation of the join() method:


当一个线程终止this.notifyAll方法被调用。建议应用程序不要在Thread实例上使用wait,notify或notifyAll。

As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

这篇关于如果在Thread上调用java wait(),则该方法也会在run()方法终止时退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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