java : wait() method keeps waiting even after calling notifyAll()

标签 java multithreading wait notify

考虑以下代码

public class ThreadTest1
{
private static final long startTime = System.currentTimeMillis();

    public static void main(String args[])
    {
        Thread ct = new Thread(new ChildThread());
        ThreadTest1.print("starting child threads in MAIN");
        ct.start();
        synchronized(ct)
        {
            try
            {

            ThreadTest1.print("about to start wait() in MAIN");
            ct.wait();
            ThreadTest1.print("after wait() in MAIN");
            }
            catch(Exception e)
            {
            ThreadTest1.print("Exception in MAIN");
            }
        }
    }

    public static void print(String s)
    {
    System.out.println("Millisecond : "+(System.currentTimeMillis()-ThreadTest1.startTime)+"\t: "+s);
    }
}

class ChildThread implements Runnable
{
    public void run()
    {
        synchronized(this)
        {

        try
        {
        ThreadTest1.print("before thread notifyAll in CHILD");
        notifyAll();
        ThreadTest1.print("notifyAll over, sleep starts in CHILD");
        Thread.sleep(10000);
        ThreadTest1.print("after thread sleep in CHILD");

        }
        catch(Exception e)
        {
        ThreadTest1.print("Exception in CHILD");
        }
        ThreadTest1.print("End of run method in CHILD");
        }
    }
}

输出如下:

Millisecond : 12        : starting child threads in MAIN
Millisecond : 13        : about to start wait() in MAIN
Millisecond : 13        : before thread notifyAll in CHILD
Millisecond : 13        : notifyAll over, sleep starts in CHILD
Millisecond : 10015     : after thread sleep in CHILD
Millisecond : 10015     : End of run method in CHILD
Millisecond : 10016     : after wait() in MAIN

notifyAll() 在第 13 毫秒被调用。但是控制仅在第 10016 毫秒时才从 wait() 中出来。

从上面给出的代码来看,似乎 wait() 调用没有在 notify() 调用后立即结束。

但是所有文件包括Java API , 指定调用 wait() 的方法应在 notify() 调用后立即获取锁。

如果调用 notify() 时 wait() 不会结束,那么对 notify() 的需求就变得无效了,因为调用 wait() 的方法会在新线程的 run 方法结束时自动获得控制权,即使未调用 notify()。

如果我在这里犯了错误,请等待有人指出。

最佳答案

问题是您正在通知和等待不同的 对象。您在 Threadwait() 并在 run() 方法中调用 this ...这是一个 ChildThread


由于您错误命名了您的 ChildThread 类,这一点被掩盖了。该名称​​暗示它是一个Thread 子类,但它实际上是一个Runnable 子类。

关于java : wait() method keeps waiting even after calling notifyAll(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20334637/

相关文章:

java - 导入另一个spring项目的spring项目

Java 嵌套类实例防止外部类GC

multithreading - CompletableFuture 重用池中的线程

java - 由同一对象同步的 Wait-Notify 不起作用

java - 为什么 findbugs 会为一种方法提供冗余的 nullcheck 而不是另一种方法

python - 在Python中,我应该为此使用线程吗?

multithreading - C++ AMP 中 1D 和 2D 数组上的运算符 [] 的行为。

c# - await Task.Delay() 与 Task.Delay().Wait()

Java wait() 不抛出 InterruptedException

java - 从可能为空的 Double 创建的 BigDecimal 的总和