I wanted to write a program about notifyAll:

Code:
  



public class Main {
    
    /** Creates a new instance of Main */
    
    
        public static void main(String[] args) {
        // TODO code application logic here
        distanceshow d=new distanceshow();
       
                 
        Thread thread1 = new Thread(d);
        Thread thread2 = new Thread(d);
        Thread thread3 = new Thread(d);
        thread1.start();
        thread2.start();
        thread3.start(); 
    }
    
}

Code:
  public class distanceshow implements Runnable  {
    
    /** Creates a new instance of distanceshow */
   int i;
   int d;
    
    public static int distance=100;
   
       public void run()
            {
         if(i<3){
          i++;
          System.out.println(" Runner number" +'\t' + i +'\t'+"is ready");
           try{
                wait ();
              }
         catch (InterruptedException e) { }
         } else if(i==3){
                
             notifyAll();     
             System.out.println(" START");
             for ( i=100;i<=400;i+=100){
                 System.out.println("distance="+ i );
             }
                 
                 
            }
    
       }
}

The goal of this program is :

we have three runners , when they are ready for run ,

We must print :

Runner number 1 is ready
Runner number 2 is ready
Runner number 3 is ready

START

after that, I want this program shows something like this:

Runner number 1 distance is 100
Runner number 3 distance is 200
Runner number 2 distance is 300
Runner number 4 distance is 400

Runner number 4 wins!


But, I have problmes :

1-When I compile this , These errors shows:


compile:
run:
Runner number 2 is ready
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
Runner number 1 is ready
at java.lang.Object.wait(Native Method)
Runner number 3 is ready
at java.lang.Object.wait(Object.java:485)
at notifyalltest.distanceshow.run(distanceshow.java:29)
at java.lang.Thread.run(Thread.java:619)
Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at notifyalltest.distanceshow.run(distanceshow.java:29)
at java.lang.Thread.run(Thread.java:619)
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at notifyalltest.distanceshow.run(distanceshow.java:29)
at java.lang.Thread.run(Thread.java:619)
BUILD SUCCESSFUL (total time: 0 seconds)


why?

2-

in order to print this part, Which way do you suggest?

Runner number 1 distance is 100
Runner number 3 distance is 200
Runner number 2 distance is 300
Runner number 4 distance is 400

Runner number 4 wins!