O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required