gpt4 book ai didi

java - 线程.getState()

转载 作者:行者123 更新时间:2023-11-30 04:19:10 26 4
gpt4 key购买 nike

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

最佳答案

您没有将线程数组中的索引分配给非空值。您创建它们,但从未将它们分配给数组中的索引,因此这些索引为空。

这是对您的代码的更正:

for(int i=0;i<threads.length;i++){
MatrixThread thread = new MatrixThread(count);
threads[i] = thread;
count++;
}

我不建议扩展线程。尝试实现 runnable,并将 runnable 传递给线程。我可以详细说明原因 but its already been done.

Thread.isAlive 可能就是您正在寻找的。我建议做类似的事情......

runnable.setActive(false);
//this will block invoking thread for 1 second, or until the threadRunningRunnable terminates
threadRunningRunnable.join(1000);
//for the paranoid programmer...
if(threadRunningRunnable.isAlive()){
//something very bad happened.
}

关于java - 线程.getState(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17556871/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com