| Author |
Question on multithreading from Sierra/Bates Chapter 9, Question 16
|
Sandra Bachan
Ranch Hand
Joined: Feb 18, 2010
Posts: 434
|
|
Sierra/Bates Chapter 9, question 16:
Even though the code compiles, it gives the following run-time error:
Exception in thread "Thread-0" java.lang.NullPointerException
at ChicksYack.run(ChicksYack.java:20)
at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-1" java.lang.NullPointerException
at ChicksYack.run(ChicksYack.java:20)
at java.lang.Thread.run(Unknown Source)
Explaination is that c should be assigned to an object. Isn't c already assigned to an object in go() on line 15?
|
Marriage Made in Heaven
http://www.youtube.com/user/RohitWaliaWedsSonia
|
 |
Neha Daga
Ranch Hand
Joined: Oct 30, 2009
Posts: 504
|
|
|
yes, but its initialised inside a method which means its limited to that method only.
|
SCJP 1.6 96%
|
 |
Shanky Sohar
Ranch Hand
Joined: Mar 17, 2010
Posts: 1046
|
|
the code will compile because at compile time compiler is not able to find any errro.............
but as object are created at runtime..........so when JVM reaches
c.yack(Thread.currentThread().getId());
JVM not able to find any object to which "c" refers to.........
although you have done c = new Chicks();
within a go() method....but it will remain within a go method only......
but if you make
Chick c; as " static Chick c;" then below code will compile...................
or if you do c = new Chicks(); within a run() method then it will also compile.............
|
SCJP6.0,My blog Ranchers from Delhi
|
 |
Abimaran Kugathasan
Ranch Hand
Joined: Nov 04, 2009
Posts: 2066
|
|
|
What about the ChicksYack object in the line 16 and 17? Do they have not null c object?
|
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
|
 |
Sandra Bachan
Ranch Hand
Joined: Feb 18, 2010
Posts: 434
|
|
Now I understand - the concept of multithreading must have overshadowed the simple concept of scope. Below is the corrected code:
|
 |
Shanky Sohar
Ranch Hand
Joined: Mar 17, 2010
Posts: 1046
|
|
|
yeah you got it...........
|
 |
 |
|
|
subject: Question on multithreading from Sierra/Bates Chapter 9, Question 16
|
|
|