I am new to using threads, and I'm trying to figure out a way to tell if a thread is terminated, as well as gather some information from the thread. However, I'm getting a null pointer exception whenever I try to call a method of one of the threads including thread.getState(). Please I would like some insight as to how a thread works in java with respect to how I am using it.
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;
}
}
And then when I run my program it looks like this
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++;
}
}
}
}
execution in the main process stops on "thread.getState()" because of a null pointer exception. Any ideas why?