Java Multithreading null pointer exception -
i'm working on program , keep getting nullpointerexception , i'm not sure why.
//constructor public longtask(sharedresults shareddata,int start, int end) { super("thread"); shareddata=this.shareddata; start = this.start; end=this.end; } //run public void run() { int sum = 0; (int num = start; num<=end;num++) { sum+=num; try { thread.sleep((long)(5000*math.random())); } catch (interruptedexception e) {} shareddata.addtoresult(sum); } } }
i end getting nullpointerexception error. looks data not being summed correctly.
your problem is:
shareddata=this.shareddata; start = this.start; end=this.end;
you assigned method level variables have values of class level variables. needs other way around. way it's written now, shareddata null
because it's never getting assigned in constructor. later, when call
shareddata.addtoresult(sum);
you calling attempting call method on null object reference, explains nullpointerexception
.
Comments
Post a Comment