我是新手使用线程,我正试图找出一种方法来判断线程是否被终止,以及从线程中收集一些信息。 但是,每当我尝试调用其中一个线程(包括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()”上停止。 有什么想法吗?