Showing posts with label thread. Show all posts
Showing posts with label thread. Show all posts

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

Sunday, June 26, 2011

Funny thing about Java thread

Other day, I was trying to store a thread reference which could be started whenever needed. To surprise, it threw IllegalThreadStateException. After searching I figured out that threads can be started only ones..rightly as javadoc says "It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution."

So you have 3 options :
- Use thread suspend/resume
- Do not allow it to end, use Thread.sleep(time)
- Create new thread as needed