java - notifyall() - On threads that use static synch method -




i have following code trying print threads according id 0,1,2 : reason notifyall() not working me, prints first thread , seems other keeps waiting.

public class workthread extends thread {      private int[] vec;     private int id;     private int res;     static integer printnowid = 0;      public workthread(int[] vec, int id) {         this.vec = vec;         this.id = id;     }      public  synchronized void checkturn(int id){         while (id != printnowid){             try {                 wait();             } catch (interruptedexception e) {                 // todo auto-generated catch block                 e.printstacktrace();             }         }     }      public  synchronized void done(){         printnowid = printnowid + 1 ;         notifyall();     }      public static synchronized int p(int[] vec, int id){         int res = 0;          for(int i=0;i<vec.length;i++){             vec[i] = vec[i] + 1;              res = res +vec[i];         }          return res;     }      public  void run () {         res = p(vec,id);         checkturn(id);         system.out.println("task " + id + " res= " + res);         done();     } } 

public class driverabcd {

public static void main(string[] args) throws interruptedexception {      int vec[] = {1,2,3,4};     workthread[] workers = new workthread[3];     for(int i=0;i<3;i++){         workers[i] = new workthread(vec,i);     }      for(int i=0;i<3;i++){         workers[i].start();     }      system.out.println("main"); 

}

only first thread printed. , other not.

you using wrong locking objects. lock on each workthread, workthread 0 not release workthread 1 or 2 , vice versa.

what need 1 locking object workthread synchronize. can following changes code.

public class workthread extends thread { ...    static object lock = new object(); ...    public void checkturn(int id) {      synchronized (lock) {         while (id != printnowid) {             try {                 lock.wait();             } catch (interruptedexception e) {                 e.printstacktrace();             }         }      }   }     public void done() {      synchronized (lock) {         printnowid = printnowid + 1;         lock.notifyall();      }    } ... 

the output looks like:

task 0 res= 14 main task 1 res= 18 task 2 res= 22 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -

python - Read npy file directly from S3 StreamingBody -