Consider the following code:
class Chicks {
synchronized void yack(long id) {
for(int x = 1; x < 3; x++) {
System.out.print(id + " ");
Thread.yield();
}
}
}
public class ChicksYack implements Runnable {
Chicks c; //.....(1)
public static void main(String[] args) {
new ChicksYack().go();
}
void go() {
c = new Chicks(); //........(2)
new Thread(new ChicksYack()).start();
new Thread(new ChicksYack()).start();
}
public void run() {
c.yack(Thread.currentThread().getId());
}
}
When i run this code, I am getting a Null Pointer Exception that I have not initialized variable c. But didn't i initialized it at line ....(2)? I am having trouble getting this concept. Does threading has a part to play in this exception?