【问题标题】:thread.getState()线程.getState()
【发布时间】:2013-07-09 19:46:39
【问题描述】:

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

【问题讨论】:

标签: java multithreading parallel-processing


【解决方案1】:

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

以下是对您的代码的更正:

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.
}

【讨论】:

  • 没问题。如果您没有更多问题,请接受关闭此问题的答案。如果您还有其他问题,请提出!
【解决方案2】:

thread.getState() 正在查找存储在数组索引中的任何内容的状态,但是由于没有分配任何值,因此它们没有状态。因此,当 getState 查看数组时,它没有找到任何要返回的状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 2018-08-17
    • 2019-07-25
    • 2014-02-21
    • 2014-09-26
    • 2021-10-22
    • 1970-01-01
    相关资源
    最近更新 更多