Pages

2011-01-12

Stop a Java thread properly

public class myThread extends Thread {
      // define a volatile Boolean as a trigger for thread stop
      private volatile boolean stop = false;

     
      @Override
      public void run() {
            while(!stop) {
                 
                  //do some reoccurring task here

                  ....
 

                  //wait
                  try {
                        new Thread();
                        Thread.sleep(1000);
                  } catch (InterruptedException e) {
                        stop = true;
                  }
            }
      }
      public void destroy() {
            stop=true;
            interrupt();
      }
}

Run the thread and stop it using the destroy() method.

That's it!

No comments:

Post a Comment