0

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

Symlink
  • 383
  • 2
  • 12
  • 1
    You may be able to find an answer here: https://stackoverflow.com/questions/16758346/how-pause-and-then-resume-a-thread – Asotos Jun 16 '19 at 22:07
  • 2
    That's why you can attach a debugger to a JVM. All popular IDE's support debugging Java applications, and inside the debugger you can set breakpoints, pause a thread, step through the code, etc. – Erwin Bolwidt Jun 16 '19 at 22:18

1 Answers1

0

Use a debugger such as IntelliJ or Eclipse, which have built-in functionality to set breakpoints, which then pause execution of the application while you inspect variables, etc.

Jason
  • 11,744
  • 3
  • 42
  • 46