简体   繁体   中英

Java wait notify - notify notifies all threads

I have two classes that extend Thread and a wait/notify

class A extends Thread {

    int r = 20;

    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (this) {
            notify();
        }
    }
}

class B extends Thread {

    A a;

    public B(A a) {
        this.a = a;
    }

    public void run() {
        synchronized (a) {
            System.out.println("Starting...");
            try {
                a.wait();
            } catch (InterruptedException e) {
            }
            System.out.println("Result is: " + a.r);
        }
    }
}

Class A notifies Class B upon end of execution

A a = new A();
new B(a).start();
new B(a).start();
new B(a).start();

And the following code

a.start();

Notifies all threads

new Thread(a).start(); 

Notifies one thread

Why does a.start() notify all threads?

It's not

a.start();

that notifies all threads. It's the fact that the thread referenced by a terminates that notifies all threads waiting on its monitor.

This is explained in the javadoc

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

On the other hand, in

new Thread(a).start(); 

you're using a as a Runnable , not as a Thread . The actual thread that will invoke this.notifyAll is the one created by the instance creation expression new Thread(a) , which no other thread has called Object#wait() on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM