多线程中线程没有notify()退出等待状态

Thread come out from waitting state without notify() in multithreading

ThreadB没有执行notify(),ThreadA应该一直在waiting状态,下面的代码怎么执行呢。 当另一个线程完成执行时,一个线程是否有可能从等待状态中退出。

public class ThreadA extends Thread
{
    public static void main(String[] args)
    {
        ThreadB B = new ThreadB();
        B.start();
        synchronized (B) {
            try {
                /* Go into waiting state */
                B.wait();
            } catch (InterruptedException e) {
            }

            System.out.println(B.result);
        }
    }
}

class ThreadB extends Thread
{
    int result;

    public void run()
    {
        synchronized (this) {
            for (int i = 0; i <= 10; i++) {
                result = result + i;
            }
            // notify();
        }
    }
}

输出:

55

如果您转到 JavaDocs (http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()) 并阅读 Thread 的文档,您会看到它说永远不要在 Thread 上使用 wait、notify 或 notifyAll。在内部,Thread.join() 和线程死亡使用 wait 和 notifyAll 来完成连接功能

当线程 ends/exists 时,它将 notifyAll 在其实例上。这就是你看到的。