Java Reference
In-Depth Information
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;
}
TryThreadInterrupted.java
I created this as a new example in the download called TryThreadInterrupted . Of course, some of the
code in main() has to be changed accordingly. Now the program produces output that is something like
the following:
Press Enter when you have had enough...
Slim Hopalong Marilyn Cassidy
Hopalong Monroe
Marilyn Cassidy
Hopalong Pickens
Slim Cassidy
Hopalong Monroe
Marilyn
Enter pressed...
Search WWH ::




Custom Search