Monday, February 3, 2014

How do I determine if a thread is alive or not?

n Java, a thread is considered to be alive when its start() method has been called. After the run() method finishes, the thread is considered to not be alive anymore. We can determine if a thread is currently alive or not by calling a Thread instance's isAlive() method. The getState() method can also be useful. It returns a Thread.State enum representing the current state of the thread.
We can demonstrate these methods with a simple example. First, we'll implement a job to be run by a thread called RunnableJob.

RunnableJob.java

package com.cakes;

public class RunnableJob implements Runnable {

 @Override
 public void run() {
  System.out.println("RunnableJob is running");
 }

}
Next we'll create a ThreadExample class. This class creates a Thread instance with a RunnableJob instance. After creating this thread, we call getState() and isAlive() on the thread. After this, we start the thread via its start() method. Once again, we call getState() and isAlive(). After that, we pause the current thread of execution for one second, and then we once again call getState() and isAlive().

ThreadExample.java

package com.cakes;

public class ThreadExample {

 public static void main(String[] args) throws InterruptedException {

  RunnableJob runnableJob = new RunnableJob();
  Thread thread = new Thread(runnableJob);

  displayStateAndIsAlive(thread);
  thread.start();
  displayStateAndIsAlive(thread);
  Thread.sleep(1000);
  displayStateAndIsAlive(thread);
 }

 public static void displayStateAndIsAlive(Thread thread) {
  // java.lang.Thread.State can be NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
  System.out.println("State:" + thread.getState());
  System.out.println("Is alive?:" + thread.isAlive());
 }

}
The console output of the execution of ThreadExample is shown here. Notice that when the thread has been created but not started, its state is NEW and it is not alive. After we start the thread, its state is RUNNABLE and it is alive. During the second-long pause, we can see from the console output that the run() method of our job has been called. After the pause, the state of the thread is TERMINATED and the thread is no longer alive.

Console Output

State:NEW
Is alive?:false
State:RUNNABLE
Is alive?:true
RunnableJob is running
State:TERMINATED
Is alive?:false

No comments:

Post a Comment