How can i know if the Daemon was stopped from a different thread

111 views Asked by At

My Daemon create and runs a function on a different thread this function runs many other functions. I want to check before each function if the Daemon was closed and if not then i will perform the function. How can i know if the Daemon was stopped?

3

There are 3 answers

0
Anonymous Coward On
class Daemon extends Thread()
{
  private boolean started;
  public void Daemon() {
    started = false;
  }
  public void run() {
    started = true;
    // rest of your code.
  }

  public boolean isStoped() {
    return started && !isAlive();
  }
}

Use isStoped() to know when your thread has been stoped. isAlive() alone is not enough because a thread which has not been started will return false.

0
sjain On

When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.

If you don't know if the thread is daemon or not then use isDaemon,

isDaemon

public final boolean isDaemon()

Tests if this thread is a daemon thread.

Returns: true if this thread is a daemon thread; false otherwise.

Then you can ask the Thread for its current status by calling:

Thread.State ts = thread.getState();

and you should get one of the follwing:

A thread state. A thread can be in one of the following states:

  • NEW A thread that has not yet started is in this state.

  • RUNNABLE A thread executing in the Java virtual machine is in this state.

  • BLOCKED A thread that is blocked waiting for a monitor lock is in this state.

  • WAITING A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

  • TIMED_WAITING A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.

  • TERMINATED A thread that has exited is in this state.

Reference: http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#isDaemon()

0
Enerccio On

Just like any other thread, you have to get the thread instance and then call:

thread.isAlive()