java - Why notify() is not working in below code? -


i want print odd number in order 1 2 3 4 5 6. think first notify call in odd-thread should unblock even-thread wait() print next number not case. printing "1"

class t1 extends thread {     private string[] s1;     private boolean flag;      public t1(string[] args, boolean flag) {         this.flag = flag;         this.s1 = args;     }      public synchronized void run() {         (int = 0; < s1.length; i++) {             if(flag)             {                 try {                    wait();                 } catch (interruptedexception e) {                    system.out.println("exception");                 }             }             system.out.println(s1[i]);             notify();             flag = true;         }     } }  public class testthread {     public static void main(string[] args) {         string[] s1 = { "1", "3", "5" };         string[] s2 = { "2", "4", "6" };          runnable odd = new t1(s1,false);         runnable = new t1(s2,true);          new thread(even,"even-thread ").start();         new thread(odd,"odd-thread ").start();      } } 

as others point out, 2 threads use different monitors, should use shared object monitor.

however, fixing not solve problems. see opportunity missed signal. (one thread may call notify, when other isn't waiting).

all in don't regard of guidelines should used wait-notify.

from java concurrency in practice :

when using condition waits (object.wait or condition.await):

  • always have condition predicate—some test of object state must hold before proceeding;
  • always test condition predicate before calling wait, , again after returning wait;
  • always call wait in loop;
  • ensure state variables making condition predicate guarded lock associated condition queue;
  • hold lock associated the condition queue when calling wait, notify, or notifyall; and
  • do not release lock after checking condition predicate before acting on it.