Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread waiting another thread

I need an explanation here.

 public static void main(String[] args) {
    FirstThread obj = new FirstThread();
    for (int i = 1; i <= 10; i++) {
      new WaiterThread(obj).start();
    }
    obj.start();
  }

public class FirstThread extends Thread {
  @Override
  public void run() {
    // Do something
  }
}


public class WaiterThread extends Thread {
  Object obj;

  WaiterThread(Object obj) {
    this.obj = obj;
  }

  @Override
  public void run() {
    synchronized (obj) {
           obj.wait();
    }
  }
}

10 threads are created for WaiterThread and are waiting for a single FirstThread object. After FirstThread terminates, all WaiterThread s resumed without obj.notify() or obj.notifyAll() being called anywhere.

Does that mean WaiterThread s stopped waiting for FirstThread because it gets terminated?

like image 634
Mawia Avatar asked Dec 16 '22 07:12

Mawia


2 Answers

As per the documentation of the Thread class, a dying thread calls notifyAll on the instance which represents it.

Furthermore, quoting the same documentation:

It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

Of course, the same recommendation applies to instances of Thread subclasses, which is what your code is doing.

like image 59
Marko Topolnik Avatar answered Dec 29 '22 17:12

Marko Topolnik


This is a side-effect of the fact that when a thread terminates, it invokes this.notifyAll() (as documented in the javadoc of Thread.join()). The same javadoc also makes the following recommendation:

It is recommended that applications not use wait, notify, or notifyAll on Thread instances

like image 45
JB Nizet Avatar answered Dec 29 '22 18:12

JB Nizet