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.
source share