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 I declare it as static
public static void main(String[] args) {
new ChickYacks().go();
}
public void run()
{
c.yacks(Thread.currentThread().getId()); //Throws a Nullpointer exceptin
}
void go()
{
c = new Chicks();
new Thread(new ChickYacks()).start();
new Thread(new ChickYacks()).start();
}
}
Why does it throw a Nullpointer exception in run method()
. Everything looks fine to me. When I declare Chicks 'c'
as static but I am not understanding it why?
Your go
method assigns a non-null value to "this" instance of ChickYacks
- but then creates two new instances of ChickYacks
, each of which will have a null value for c
.
You could:
c
in a constructor instead, so that each instance has a non-null valuec
in a field initializerc
in the run()
methodc
for the new instances in the go
methodthis
to the Thread
constructor instead of creating new instancesc
static so that it doesn't matter which instance you access it from (or indeed whether you access it in a static method instead; it would be associated with the type rather than with instances)This has nothing to do with threading, really. You'd get the same sort of effect if you didn't use threads, just with the exception being thrown in the original thread instead of new threads:
void go()
{
c = new Chicks();
new ChickYacks().run(); // Bang!
new ChickYacks().run();
}