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
cin constructor instead, each instance has non-null value - initialize
cin field initializer - initialize
cinrun()method - initialize
cnew instances ingomethod - pass
thisthreadconstructor instead of creating new instances - make
cstatic 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
Post a Comment