如何获得线程的状态?

时间:2011-05-06 08:32:06

标签: java multithreading

这是我定义我的线程的方式

public class Countdown implements Runnable{

    public Countdown(){
        new Thread(this).start();
    }

    //...
}

如果以这种方式启动,是否仍然可以获得线程的状态?像

 Countdown cd = new Countdown();
 cd.getState();

5 个答案:

答案 0 :(得分:6)

  

如果以这种方式启动线程,是否仍然可以获得线程的状态?

没有。事实并非如此。

如果你想获得状态,你必须保持对线程的引用; e.g。

public class Countdown implements Runnable{
    private final Thread t;

    public Countdown(){
        t = new Thread(this);
        t.start();
    }

    public Thread.State getState() {
        return t.getState();
    }
    // ...
}

顺便说一句,还有其他原因导致这不是一个很好的模式:

  • 如果对Countdown对象的引用丢失(例如由于构造父对象时出现异常),则会泄漏一个线程。

  • 线程和线程创建会消耗大量资源。如果有很多这些Countdown个对象,或者它们的生命周期很短,那么你最好使用一个线程池。

答案 1 :(得分:3)

你可以做到

public class Countdown implements Runnable{
    private final Thread thread;
    public Countdown(){
        (thread = new Thread(this)).start();
    }

    public Thread.State getState() {
        return thread.getState();
    }
}

答案 2 :(得分:2)

由于它只实现Runnable,你必须提供一个包装方法来获取状态:

class Countdown implements Runnable {
    private final Thread thread;

    public Countdown() {
        thread = new Thread(this);
        thread.start();
    }

    public Thread.State getState() {
        return thread.getState();
    }
}

答案 3 :(得分:1)

很抱歉,但是你永远不应该从构造函数中启动一个线程。那个建筑师正在乞求问题。更改,以便Countdown的实例化器创建线程。

答案 4 :(得分:1)

我建议使用run()方法并在那里分配正在运行的线程,在c-tor中没有。 有点像。

public class Countdown implements Runnable{
volatile Object thread = State.NEW;
public void run(){
  this.thread = Thread.currentThread();
  try{
///....
  }finally{
    this.thread = State.TERMINATED;
  }

}

State getState(){
  Object t=this.thread;
  return t instanceof State?((State)t):((Thread)t).getState();
}

}

相关问题