我有线程“main”java.lang.NullPointerException

时间:2014-01-23 14:39:07

标签: java object nullpointerexception

在此代码中,我遇到NullPointerException错误:

int k=3;
Thread[] th = null ;
for(int i=0; i<k; i++){
    th[i] = new ThreadF(step[i],step[i+1],"Th"+(i+1));                       
}

但是这没有错误,一切都很好:

Thread th1 = new ThreadF(step[0],step[0+1],"Th1");
Thread th2 = new ThreadF(step[1],step[1+1],"Th2");
Thread th3 = new ThreadF(step[2],step[2+1],"Th3");

为什么呢?

1 个答案:

答案 0 :(得分:4)

Thread[] th = null;

应该是:

Thread[] th = new Thread[k];

如果启用警告或使用IDE,您应该看到:

  

空指针访问:变量th在此位置只能为空