Results 1 to 1 of 1
  1. #1
    Java Tip's Avatar
    Java Tip is offline Moderator
    Join Date
    Nov 2007
    Posts
    1,694
    Blog Entries
    430
    Rep Power
    10

    Default The safe way to stop a thread

    The following Java tip shows the safe way to stop a thread. A timer is used to stop a thread after 500 milliseconds.

    Java Code:
    import java.util.Timer;
    import java.util.TimerTask;
    
    class CanStop extends Thread {
      // Must be volatile:
      private volatile boolean stop = false;
    
      private int counter = 0;
    
      public void run() {
        while (!stop && counter < 10000) {
          System.out.println(counter++);
        }
        if (stop)
          System.out.println("Detected stop");
      }
    
      public void requestStop() {
        stop = true;
      }
    }
    
    public class Stopping {
      public static void main(String[] args) {
        final CanStop stoppable = new CanStop();
        stoppable.start();
        new Timer(true).schedule(new TimerTask() {
          public void run() {
            System.out.println("Requesting stop");
            stoppable.requestStop();
          }
        }, 500); // run() after 500 milliseconds
      }
    }
    Last edited by Java Tip; 04-09-2008 at 07:34 PM.

Similar Threads

  1. Are Local variables thread safe ?
    By samson in forum Threads and Synchronization
    Replies: 6
    Last Post: 12-21-2010, 03:34 PM
  2. Struts framework. Is this thread safe?
    By JavaAl2 in forum Web Frameworks
    Replies: 1
    Last Post: 01-17-2008, 04:01 AM
  3. Local Variables for a static method - thread safe?
    By mikeg1z in forum Advanced Java
    Replies: 1
    Last Post: 11-16-2007, 02:06 AM
  4. how to stop refreshing page
    By cecily in forum New To Java
    Replies: 1
    Last Post: 07-24-2007, 02:25 AM
  5. stop button in the browser
    By Peter in forum Java Servlet
    Replies: 2
    Last Post: 07-04-2007, 08:21 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •