java - Multi threading instance field implementation -


public class chicks {     synchronized void yacks(long id)     {         for(int x = 1; x<3; x++)         {             system.out.println(id + " ");             thread.yield();         }     } } class chickyacks implements runnable {     chicks c; // no exception if declare static     public static void main(string[] args) {         new chickyacks().go();     }     public void run()     {         c.yacks(thread.currentthread().getid()); //throws nullpointer exceptin     }     void go()     {         c = new chicks();         new thread(new chickyacks()).start();         new thread(new chickyacks()).start();     } } 

why throw nullpointer exception in run method(). looks fine me. when declare chicks 'c' static not understanding why?

your go method assigns non-null value "this" instance of chickyacks - creates 2 new instances of chickyacks, each of have null value c.

you could:

  • initialize c in constructor instead, each instance has non-null value
  • initialize c in field initializer
  • initialize c in run() method
  • initialize c new instances in go method
  • pass this thread constructor instead of creating new instances
  • make c static doesn't matter instance access (or indeed whether access in static method instead; associated type rather instances)

this has nothing threading, really. you'd same sort of effect if didn't use threads, exception being thrown in original thread instead of new threads:

void go() {     c = new chicks();     new chickyacks().run(); // bang!     new chickyacks().run(); } 

Comments