I have a problem with figuring out a good way to write an application that runs on its own thread. One should be able to start and stop it and while its running to pause and unpause.
public abstract class Application implements Runnable {
private Thread runningThread;
private volatile boolean isRunning;
private volatile boolean isPaused;
public Application() {
serverThread = null;
isRunning = false;
isPaused = false;
}
public synchronized void start() {
if(!isRunning) {
isRunning = true;
serverThread = new Thread(this);
serverThread.start();
}
}
public synchronized void stop() {
if(isRunning) {
isRunning = false;
try {
serverThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void pause() {
if(isRunning && !isPaused) {
isPaused = true;
}
}
public synchronized void unpause() {
if(isRunning && isPaused) {
isPaused = false;
}
}
protected abstract void setUp();
protected abstract void update();
protected abstract void cleanUp();
@Override
public void run() {
setUp();
while(isRunning) {
if(!isPaused) {
update();
}
}
cleanUp();
}
}
The worst thing is, that it can be very difficult to propperly debug a program running on a different thread