Results 1 to 1 of 1
Thread: The safe way to stop a thread
-
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 06:34 PM.
Similar Threads
-
Are Local variables thread safe ?
By samson in forum Threads and SynchronizationReplies: 6Last Post: 12-21-2010, 02:34 PM -
Struts framework. Is this thread safe?
By JavaAl2 in forum Web FrameworksReplies: 1Last Post: 01-17-2008, 03:01 AM -
Local Variables for a static method - thread safe?
By mikeg1z in forum Advanced JavaReplies: 1Last Post: 11-16-2007, 01:06 AM -
how to stop refreshing page
By cecily in forum New To JavaReplies: 1Last Post: 07-24-2007, 01:25 AM -
stop button in the browser
By Peter in forum Java ServletReplies: 2Last Post: 07-04-2007, 07:21 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks