Reputation: 2422
Why am I getting NullPointerException here
package Threads;
public class Test implements Runnable {
FF d;
public static void main(String[] args) {
new Test().go();
}
void go() {
System.out.println(Thread.currentThread());
d = new FF();
new Thread(new Test()).start();
new Thread(new Test()).start();
}
public void run() {
System.out.println(d);
System.out.println(Thread.currentThread());
d.chat(Thread.currentThread().getId());//RTE
}
}
class FF {
static long flag = 0;
void chat(long id) {
if(flag == 0) {
flag = id;
}
for(int x=1;x<3;x++) {
if(flag == id) {
System.out.println("Yo");
}else {
System.out.println("dude");
}
}
}
}
//can anybody explain why I am getting NullPointerException here.I though d
reference variable was intialized in go()
method but I think it has something to do when new Thread is created.
Upvotes: 1
Views: 74
Reputation: 72884
d
is an instance field for class Test
. Initializing it for one instance of Test
does not make it initialized for all instances that are subsequently created. You have initialized this field in the go
method of the instance you create in main
. But after that, you create new instances of Test
for which their field is not initialized yet:
new Thread(new Test()).start(); // d is not initialized for the new Test() object
new Thread(new Test()).start();
One solution is to initialize the field in the constructor:
public Test() {
d = new FF();
}
Upvotes: 6
Reputation: 1902
you're creating a new Test instance and thus d is not initialized (since the thread.start method doesn't call your go method but only the run method).
Upvotes: 1