Friday, August 26, 2011

A stoppable Thread in Java

I am currently working on an application that has multiple different threads running. The threads are running loops and cannot be stopped using interrupts, because a clean up method has to run after the thread stops. Because I don't want to implement the same code for all these thread classes, I created an abstract subclass of the Thread class. The new class provides the following new functionality to its subclasses:
  1. Automatically call start up method when started
  2. Automatically call a method in an endless loop
  3. A way to stop the thread
  4. Automatically call clean up method when stopped
The implemenation of this abstract class:
package com.javaeenotes;

public abstract class AbstractStoppableThread extends Thread {

    private volatile boolean stopThread = false;

    @Override
    public final void run() {
        startUp();

        while (!stopThread) {
            runInLoop();
        }
        cleanUp();
    }

    public void stopThread() {
        stopThread = true;
    }

    protected void startUp() {
        ;
    }

    protected abstract void runInLoop();

    protected void cleanUp() {
        ;
    }
}
A subclass of this class has to provide the actual overriding implementations of the last three methods. A class that demonstrates the use of the abstract class is shown next:
package com.javaeenotes;

public class ExampleThread extends AbstractStoppableThread {

    @Override
    protected void startUp() {
        System.out.println("Thread started!");
    }

    @Override
    protected void runInLoop() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            ;
        }

        System.out.println("Running in a loop!");
    }

    @Override
    protected void cleanUp() {
        System.out.println("Cleaning up resources!");
    }

    public static void main(String[] args) {
        ExampleThread exampleThread = new ExampleThread();
        exampleThread.start();

        try {
            Thread.sleep(10000);
            exampleThread.stopThread();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
When the example is class is run, the program will output the following:
Thread started!
Running in a loop!
Running in a loop!
Running in a loop!
Running in a loop!
Running in a loop!
Cleaning up resources!
Other interesting links about stopping threads: