我是使用线程的新手,我正在尝试找出一种方法来判断线程是否终止,以及从线程中收集一些信息。但是,每当我尝试调用包括 thread.getState() 在内的线程之一的方法时,都会出现空指针异常。请我想了解线程在 java 中是如何工作的,以及我是如何使用它的。
public class MatrixThread extends Thread{
private int num;
private String ref;
private boolean finished;
JsonObject json = new JsonObject();
public MatrixThread(int number){
super("Matrix Thread");
System.out.println("Running Thread: " +number);
num = number;
json = object;
finished = false;
start();
}
public void run(){
System.out.println("Thread #" + num + "Has begun running");
boolean again = true;
while(again){
//Does something
if(wasSuccessful()) {
ref = operation
System.out.println("Success");
finished = true;
} else System.out.println("Did not work try again");
} catch (IOException e) {
System.out.println("Error, Try again");
}
}
}
public boolean isFinished(){
return finished;
}
public String getRef(){
return ref;
}
public int getNum(){
return num;
}
}
然后当我运行我的程序时,它看起来像这样
public static void main(String[] args) {
MatrixThread[] threads = new MatrixThread[10];
String[] refs = new String[100];
int count = 0;
for(MatrixThread thread : threads){
thread = new MatrixThread(count);
count++;
}
while(count < 100){
for(MatrixThread thread : threads){
if(thread.getState() == Thread.State.TERMINATED){
refs[thread.getNum()] = thread.getRef();
thread = new MatrixThread(count);
count++;
}
}
}
}
由于空指针异常,主进程中的执行在“thread.getState()”处停止。任何想法为什么?