Here is a simple thread pattern that I use when writing a class that needs just one thread, and needs to a specific task.
The usual requirements for such a class are that it should be startable, stopable and restartable. Does anyone see any issues with this pattern that I use?
public class MyThread implements Runnable {
private boolean _exit = false;
private Thread _thread = null;
public void start () {
_exit = false;
if (_thread == null) {
_thread = new Thread(this, "MyThread");
_thread.start();
}
}
public void run () {
while (!_exit) {
//do something
}
}
public void stop () {
_exit = true;
if (_thread != null) {
_thread.interrupt();
_thread = null;
}
}
}
I am looking for comments around if I am missing something, or if there is a better way to write this.