开发者

How to get the state of a thread?

this is how I define my thread

public class Countdown implements Runnable{

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

    //...
}

Is it still pos开发者_StackOverflowsible to get the state of a thread if it is started that way? Like

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


Is it still possible to get the state of a thread if it is started that way?

No. It is not.

If you want to be able to get the state, you have to keep a reference to the Thread; 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();
    }
    // ...
}

By the way, there are other reasons why this is not a great pattern:

  • If the reference to the Countdown object is lost (e.g. because of an exception during construction of the parent object), you will leak a Thread.

  • Threads and thread creation consume a lot of resources. If there are a lot of these Countdown objects, or if they have a short lifetime, then you'd be better of using a thread pool.


You can do

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

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


Since it's only implementing Runnable you'll have to provider a wrapper method to get the state:

class Countdown implements Runnable {
    private final Thread thread;

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

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


I'd recommend using the run() method and assign the running thread there, no in the c-tor. Something along the lines.

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();
}

}


Sorry to say, but you should never start a thread from the constructor. That constuctor is begging for problems. Change so that the instantiator of Countdown is creating the thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜