Need help starting Start / Resume / Pause / Stop thread for Selfmade Hamster Simulator

Project:

Fully recreate the famous hamster simulator using Java, currently working on buttons to start / pause / resume / stop the simulation, which works like a thread. Screenshot of current progress

Problem:

Since the user can enter loops in the editor, my usual method of using while (! Stop) does not work, because this cycle ends only after the user input cycle has ended. See WalkInCircles () from the above figure for an explanation, with this type of input, a hard-coded time (! Stopped) will never remain.

MCVE Code

public class RunnableGame extends Thread {

private final Object lock = new Object();
private volatile boolean suspend = false, stopped = false; 

  @Override
    public void run() {
     while (!stopped){        //This loop will not be left if the user inputs any loops
        while (!suspend){    //This loop will not be left if the user inputs any loops
                /* Stripped down for readability
                method.invoke();
                updateObserver();
                */
        }
        synchronized (lock){
            try {
                lock.wait();
            } catch (InterruptedException ie){
                Thread.currentThread().interrupt();
                return;
            }
        }
    }
}

  public void suspendThread(){
    suspend = true;
}

  public void stopThread(){
    suspend = true;
    stopped = true;
    synchronized (lock) {
        lock.notifyAll();
    }
}

  public void resumeThread(){
    suspend = false;
    synchronized (lock) {
        lock.notifyAll();
    }
}

What I need

Another way to start / pause / resume / stop a thread in Java.

< 3

+4
2

, , . , , , .

, interrupted , Thread Runnables : , - , , , . ( ), , , , interrupt() .

, , , . , .

- (), , , , . , , .

+1

( , , ), ( ). , , , .

, , / .

. .., :

replace("while(", "while(!suspend && !stop &&");

( / ). ​​

.

, , , (, Thread.sleep()). , .

, , , , , , , . , , , , , .

, , , - , . System.exit(0) , , :)

+1

Source: https://habr.com/ru/post/1569149/


All Articles