Java Reference
In-Depth Information
Stopping a Thread
If we did not create the threads in the last example as daemon threads, they would continue executing
independently of main() . If you are prepared to terminate the program yourself (use Ctrl+C in a DOS
session running Java) you can demonstrate this by commenting out the call to setDaemon() in the
constructor. Pressing Enter will end main() , but the other threads will continue indefinitely.
A thread can signal another thread that it should stop executing by calling the interrupt() method for
that Thread object. This in itself doesn't stop the thread, it just sets a flag in the thread that indicates an
interruption has been requested. This flag must be checked in the run() method to have any effect. As it
happens the sleep() method checks whether the thread has been interrupted, and throws an
InterruptedException if it has been. You can see that in action by altering the previous example a little.
Try It Out - Interrupting a Thread
Make sure the call to the setDaemon() method is still commented out in the constructor, and modify
the main() method as follows:
public static void main(String[] args) {
// Create three threads
Thread first = new TryThread("Hopalong ", "Cassidy ", 200L);
Thread second = new TryThread("Marilyn ", "Monroe ", 300L);
Thread third = new TryThread("Slim ", "Pickens ", 500L);
System.out.println("Press Enter when you have had enough...\n");
first.start(); // Start the first thread
second.start(); // Start the second thread
third.start(); // Start the third thread
try {
System.in.read(); // Wait until Enter key pressed
System.out.println("Enter pressed...\n");
// Interrupt the threads
first.interrupt();
second.interrupt();
third.interrupt();
} catch (IOException e) { // Handle IO exception
System.out.println(e); // Output the exception
}
System.out.println("Ending main()");
return;
}
Now the program will produce output that is something like:
Press Enter when you have had enough...
Slim Hopalong Marilyn Cassidy
Hopalong Monroe
Marilyn Cassidy
Search WWH ::




Custom Search