The wait method wakes up without triggering a notification (NOT A RANDOM LOOK)

In the example below, the method wait()

is executed even if noify is not called, but the statement below wait()

is only executed after the thread has laurel

finished executing.

I tried using other objects to lock the hard block synchronization, this time the wait method still waits forever, can someone explain to me why the statement was executed after wait()

?

package delagation;

public class Solution extends Thread {

    static Thread laurel, hardy;

    public static void main(String[] args) throws InterruptedException {
        laurel = new Thread() {
            public void run() {
                System.out.println("A");
                try {
                    hardy.sleep(1000);
                } catch (Exception e) {
                    System.out.println("B");
                }
                System.out.println("C");
            }
        };
        hardy = new Thread() {
            public void run() {
                System.out.println("D");
                try {
                    synchronized(laurel) {
                        laurel.wait();
                        //wait method is called here, 
                        //There is not notify in this class, 
                        //but the statement below are executing
                        System.out.println(Thread.currentThread().getName());
                    }
                } catch (Exception e) {
                    System.out.println("E");
                }
                System.out.println("F");
            }
        };
        laurel.setName("laurel");
        hardy.setName("hardy");
        laurel.start();
        hardy.start();
    }
}

      

+3


source to share


1 answer


You don't need to postulate a false awakening to explain what is happening here. When laurel exits, it dispatches notifyAll to the threads that are waiting on it. (This is how Thread.join works.)

See api doc for Thread # join:



This implementation uses the this.wait loop of calls caused by this.isAlive. When the thread finishes, this this.notifyAll method is called. It is recommended that applications do not use wait, notify, or notifyAll on Thread instances.

Also, always wait in a loop using a condition; see the Oracle concurrency tutorial, especially the Guarded Blocks page. (From the description, you can see that the connection is awaiting in a loop where the isAlive condition is checked on the connected thread, so this is a good example. The connection method can be found in the jdk source for the Thread class.)

+3


source







All Articles