Thread Step

In this chapter you will learn:

  1. How to use boolean variable to stop a thread

Stop a Java thread

The stop method from Thread is deprecated. In order to stop a thread we have to use a boolean variable or similar logic to exit a thread.

The following code uses the boolean value to control when to stop a thread. The while loop checks a boolean variable. If the condition doesn't meet it will keep loop and in that way we make the thread alive.

class CounterThread extends Thread {
  public boolean stopped = false;
//jav  a 2  s. c  om
  int count = 0;

  public void run() {
    while (!stopped) {
      try {
        sleep(1000);
      } catch (InterruptedException e) {
      }
      System.out.println(count++);
      ;
    }
  }
}

public class Main{
  public static void main(String[] args) {
    CounterThread thread = new CounterThread();
    thread.start();
    try {
      Thread.sleep(10000);
    } catch (InterruptedException e) {
    }
    thread.stopped = true;
    System.out.println("exit");
  }

}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to suspend, resume, and stop a thread
Home » Java Tutorial » Thread
Thread introduction
Thread Name
Thread Main
Thread sleep
Thread Creation
Thread join and is alive
Thread priorities
Thread Synchronization
Interthread Communication
Thread Step
Thread suspend, resume, and stop
ThreadGroup
BlockingQueue
Semaphore
ReentrantLock
Executor
ScheduledThreadPoolExecutor