Stopping a Thread

public class StoppableThread extends Thread {
											private boolean done = false;
											public void run( ) {
											while (!done) {
											System.out.println("Thread running");
											try {
											sleep(500);
											}
											catch (InterruptedException ex) {
											// do nothing
											}
											}
											System.out.println("Thread finished.");
											}
											public void shutDown( ) {
											done = true;
											}
											}

If you want to create a thread that you can stop at some point prior to the completion of its execution—that is, the return from the run() method—the best way to do this is to use a boolean flag that you test at the top of a main loop. In this phrase, we create a thread by extending the Thread class with our StoppableThread class. Within the run() method, we have a while loop that checks the status of a boolean done flag. ...

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.