Saturday, July 2, 2011

Easy way of stopping Java thread gracefully

One of the easy ways of stopping thread is by use of a boolean flag. We can use a outer while loop to do our periodic task, and use combination of setStop and interrupt to end it.

Here goes the code

public class MyThread implements Runnable {
 private boolean stop;
 @Override
 public void run() {
  System.out.println("Thread starts");
  while(!stop) {
   try {
    //do something fooBar()
    System.out.println("Sleeping...");
    Thread.sleep(5000);
   } catch(InterruptedException e) {
    System.out.println("Thread was inturrupted");
   } catch(Exception e) {
    //handle error
    e.printStackTrace();
   }
   
   
  }
  System.out.println("Thread ends");
 }
 
 public void setStop(boolean stop) {
  this.stop = stop;
 }

 public static void main(String args[]) throws InterruptedException {
  MyThread m = new MyThread();
  Thread t = new Thread(m);
  t.start();
  System.out.println("Main thread Sleeping...");
  Thread.sleep(2000);
  //stop in this manner
  m.setStop(true);
  t.interrupt();
 }
}

7 comments:

  1. Java has rich concurrency API even though it doesn't provide any safe method to stop a Thread or reuse a Thread directly. Though Executor framework some what handles this by using worker thread but in many scenario a direct control is needed. By the way here is mine way of Stop Thread in Java

    ReplyDelete
  2. The producer–consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue
    http://www.youtube.com/watch?v=dUwboVZ59KM

    Learn when and How to Stop the Thread,using jconsole or JvisualVM to indetify is the thread is running
    http://www.youtube.com/watch?v=3_Bqhw0d2ko

    ReplyDelete
  3. Post is very useful. Thank you, this useful information.

    Learn Best Microsoft Training in Bangalore from Experts. Softgen Infotech offers the Best Microsoft Training Course.100% Placement Assistance, Live Classroom Sessions, Only Technical Profiles, 24x7 Lab Infrastructure Support.

    ReplyDelete