简体   繁体   中英

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

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?

与其他线程一样,您必须获取线程实例,然后调用:

thread.isAlive()
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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM