简体   繁体   中英

NullPointerException in Threads

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.

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();
}

您正在创建一个新的Test实例,因此d未被初始化(因为thread.start方法不会调用go方法,而只会调用run方法)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM