11
Stopping a Thread
The ThreadStopping program starts two Threads: a Runner and a Killer. The Runner prints a counter in a loop. The Killer chases the Runner for a given time before it stops it.
- public class ThreadStopping {
- private Runner runner;
- private Killer killer;
- private static final int DELAY = 1 * 1000;
- ThreadStopping() {
- runner = new Runner("Runner");
- killer = new Killer("Killer");
- }
- public void start() {
- runner.start();
- killer.start();
- }
- public static void main(String[] args) {
- (new ThreadStopping()).start();
- }
- private class Runner extends Thread {
- private volatile boolean halted = false;
- Runner(String s) {
- super(s);
- }
- public void run() {
- setPriority(MAX_PRIORITY);
- for (int i = 0; !halted; i++)
- System.out.println(getName() + " - " + i);
- }
- public void halt() {
- halted = true;
- }
- }
- private class Killer extends Thread {
- Killer(String s) {
- super(s);
- }
- public void run() {
- long now = System.currentTimeMillis();
- long elapsed = 0;
- while (elapsed < DELAY) {
- elapsed = System.currentTimeMillis() - now;
- System.out.println(getName() + " - " + elapsed);
- yield();
- }
- System.out.println(getName() + " - " + elapsed);
- System.out.println(getName() + " - " + "Killing " + runner.getName());
- runner.halt();
- }
- }
- }
$ javac ThreadStopping.java
$ java ThreadStopping
Killer - 0
Runner - 0
Runner - 1
Runner - 2
...
Runner - 15
Killer - 3
Killer - 5
...
Runner - 107393
Runner - 107394
Killer - 1154
Killer - Killing Runner
Runner - 107395
Runner - 107396
The output of the program shows that the Runner
and the Killer
are both running alternatively. As soon as the Killer
has run more than 1 second, it kills the Runner
. Messages from the Runner
continue to appear after it has stopped because the output buffer is flushed. Add a call to System.out.flush()
after printing messages to flush the output immediately. The program will be slower. You might still see one message after the Killer
has killed the Runner
if the Runner
was interrupted in its loop before testing the flag halted
.
Comments