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();
The method currentThread() of the Thread class can be used to obtain the current 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With