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
, , . , , , .
, interrupted , Thread Runnables : , - , , , . ( ), , , , interrupt() .
interrupted
Thread
Runnables
interrupt()
, , , . , .
- (), , , , . , , .
( , , ), ( ). , , , .
, , / .
. .., :
replace("while(", "while(!suspend && !stop &&");
( / ).
.
, , , (, Thread.sleep()). , .
Thread.sleep()
, , , , , , , . , , , , , .
, , , - , . System.exit(0) , , :)
System.exit(0)
Source: https://habr.com/ru/post/1569149/More articles:Priority queue comparator for an object with a constant member - c ++GoogleAnalytics.getInstance (this) is not responding - androidPython AES decryption - javaAzure ActiveDirectory Graph API GraphClient does not return AD groups - asp.net-mvcKendoUI Grid default with data annotation - asp.net-mvcWhat is the best way to delete over 100,000 files? - marklogicIOS application and user authentication. OAuth? - phpPython - exact number of arguments defined by a variable - pythonCross-platform C # application using Mono with nice interface - user-interfacessh with nodejs child_process, command not found on server - node.jsAll Articles