Pause and resume threads that are sleeping Java

1.3k Views Asked by At

I have a thread that is running a simulation and is iterating a step of a dynamic system in the logic layer and then repainting the GUI to see the results in the screen. In order to let the user view how the system is changing there is a sleep between each repaint, but I also need to pause the simulation to observe changes, this is stop the repainting and the iteration of the system until the user resume the simulation.

Currently looks like this:

simulationThread = new Thread(){
        @Override
        public void run(){
            for(int i=0; i<iterations; i++){
                world.iterate();
                try{
                  Thread.sleep(100);
                }catch( Exception e ){ 
                   e.printStackTrace();
                }
                view.repaint();
            }
        }
    };

    simulationThread.start();

How can I pause simulationThread and be able to resume it again?, I've tried to use wait() method, but there is problem when the thread is slept and wait is called. I suspect that I should change the way of how the thread wait until the next repaint in order to acomplish the pause/resume task but I'm not sure how.

1

There are 1 best solutions below

2
On BEST ANSWER
class Pauser
{
public:
    public synchronized void pause()
    {
         isPaused = true;
    }
    public synchronized void resume() 
    {
         isPaused = false;
         notifyAll();
    }
    public synchronized void waitIfPaused()
    {
         while(isPaused)
         {
             wait();
         }
    }
private:
    boolean isPaused;
};

Use .pause() method for pause simulation, .resume() for resume, and .waitIfPaused() inside your thread whenever it is safe to pause. E.g., you can use .waitIfPaused() before change system parameters.