Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 possible to get the state of a thread if it is started that way? Like

 Countdown cd = new Countdown();
 cd.getState();
like image 1000
UpCat Avatar asked May 06 '11 08:05

UpCat


People also ask

Which method is used to know the current state of a thread?

The method currentThread() of the Thread class can be used to obtain the current thread.

What are the state in the life cycle of a thread?

A thread goes through various stages in its lifecycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread. New − A new thread begins its life cycle in the new state.


1 Answers

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.

like image 114
Stephen C Avatar answered Oct 12 '22 05:10

Stephen C