Thread waiting for 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 for WaiterThread have been created and are waiting for one FirstThread object. After FirstThread is completed, all WaiterThread s resumes without obj.notify () or obj.notifyAll () being called anywhere.

Does this mean that WaiterThread stopped waiting for FirstThread because it is ending?

+4
source share
3 answers

According to the documentation for the Thread class, a dying thread calls notifyAll on the instance that represents it.

Also, quoting the same documentation:

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

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

+6
source

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

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

+6
source

I slightly modified the code below

Method

main () remains the same

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

changes as follows

 class WaiterThread extends Thread { Object obj; WaiterThread(Object obj) { this.obj = obj; } @Override public void run() { synchronized (obj) { try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread " + this.getId() + "started"); } System.out.println("Out of sync block by " + this.getId()); } } 

ant The result I got

 FirstThread Started Thread 19started Out of sync block by 19 Thread 18started Out of sync block by 18 Thread 17started Out of sync block by 17 Thread 16started Out of sync block by 16 Thread 15started Out of sync block by 15 Thread 14started Out of sync block by 14 Thread 13started Out of sync block by 13 Thread 12started Out of sync block by 12 Thread 11started Out of sync block by 11 Thread 10started Out of sync block by 10 

So you have your answer. They do not start at the same time! FirstThread calls notifyAll () during extinction, which notifies everything, but each thread can only lock one at a time. Thus, although each thread is notified, only one thread is executed at a time.

0
source

Source: https://habr.com/ru/post/1498338/


All Articles