More on Starting, Stopping, and Joining

Consider this revision to the Animate example:

import java.applet.Applet;

public class Animate extends Applet {
    TimerThread t;
    public void start() {
        if (t == null)
            t = new TimerThread(this, 500);
        t.start();
    }

    public void stop() {
        t.shouldRun = false;
        try {
            t.join();
        } catch (InterruptedException e) {}
        // t = null;
     }
}

In our last version of the Animate applet (see Section 2.3,” earlier in this chapter), the start() method of the applet created a new TimerThread object and started it. But what if we had only created the TimerThread once? In the example just shown, we once again create a new TimerThread in the start() method of the applet; however, since we know the thread will be stopped in the stop() method, we try to restart the stopped thread in the start() method. In other words, we create the TimerThread only once and use this one thread object to start and stop the animation. By starting and stopping a single TimerThread, we do not need to create a new instance of TimerThread every time the applet is started, and the garbage collector will not need to clean up the TimerThread instance that’s left when the applet is stopped and the TimerThread dereferenced.

But will this work? Unfortunately, the answer is no. It turns out that when a thread is stopped, the state of the thread object is set so that it is not restartable. In our case, when we try to restart the thread by calling the TimerThread’s start() method, nothing happens. The

Get Java Threads, Second Edition 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.