I am solving the below interview question. It's throwing a NullPointerException
, but I do not understand how the value of c is null. I already initialized it in the go()
method.
package swain.javainterviewhub.blogspot.in;
class Chicks{
synchronized void yack(long id){
for(int x=1;x<3;x++){
System.out.println(id+" ");
Thread.yield();
}
}
}
public class JavaInterviewHub implements Runnable {
Chicks c;
public static void main(String[] args) {
new JavaInterviewHub().go();
}
void go(){
c=new Chicks();
new Thread(new JavaInterviewHub()).start();
new Thread(new JavaInterviewHub()).start();
}
@Override
public void run() {
c.yack(Thread.currentThread().getId());
}
}
Console:
Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.NullPointerException
at swain.javainterviewhub.blogspot.in.JavaInterviewHub.run(JavaInterviewHub.java:28)
at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
at swain.javainterviewhub.blogspot.in.JavaInterviewHub.run(JavaInterviewHub.java:28)
at java.lang.Thread.run(Unknown Source)