Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't thread wait for notify()?

Why doesn't thread wait for notify()? The thread starts and then goes to the waiting pool, but it proceeds to execute after that moment.

public class JavaApplication2 {
    public static void main(String [] args) {
       ThreadB b = new ThreadB();
       synchronized(b) {
           b.start();
           try {
              System.out.println("1");
              b.wait();
         } catch (InterruptedException e) {}
          System.out.println("Total is: " + b.total);
       }
     }
 }
  class ThreadB extends Thread {   
    int total;
      @Override
    public void run() {
        synchronized(this) {
            total += 1;
            //notify();
       }
    }
 }
like image 597
Eddie Jamsession Avatar asked Dec 21 '22 11:12

Eddie Jamsession


2 Answers

You are synchronizing on the thread object itself, which is wrong usage. What happens is that the dying thread-of-execution always calls notify on its Thread object: Thread.join relies on this. Therefore it is clear why you get the same behavior with and without your own notify in there.

Solution: use a separate object for thread coordination; this is the standard practice.

like image 194
Marko Topolnik Avatar answered Dec 23 '22 00:12

Marko Topolnik


The method notifyAll() is invoked for the Thread object of the terminating thread. This fact is strangely documented in the description of the Thread.join, with the following sentence:

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

Thus, if you don't explicitly read the description of join, which you don't necessarily have to, you don't get to know the reason for the strange behavior.

like image 40
Pcgomes Avatar answered Dec 23 '22 00:12

Pcgomes