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?
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
, ornotifyAll
onThread
instances.
Of course, the same recommendation applies to instances of Thread
subclasses, which is what your code is doing.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With