gpt4 book ai didi

java - 需要帮助在自制仓鼠模拟器上实现启动/恢复/暂停/停止线程操作

转载 作者:搜寻专家 更新时间:2023-11-01 03:22:08 24 4
gpt4 key购买 nike

项目:

Completely recreate the known Hamster Simulator using Java, currently working on buttons to start/pause/resume/stop the simulation, which is running as a Thread. Screenshot of current progress

问题:

As the user can input loops into the editor, my usual method of using while(!stopped) does not work because this loop only ends after the loop the user has input has ended. See walkInCircles() from the picture above for explanation, with this kind of input the hardcoded while(!stopped) would never be left.

MCVE 代码

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();
}
}

我需要什么

A different way to start/pause/resume/stop a Thread in Java.

非常感谢转发<3

最佳答案

如果不指定缺少无限循环,我觉得这个问题本质上是不可能的。如果提供的方法的持续时间是无限的,并且您的类永远不会从该方法获得优先级,那么在它终止之前您无法与之交互。

基本上,interrupted 状态是 Thread 子类和 Runnables 必须遵循的约定:如果您所在的线程曾经变为中断你必须停止你正在做的事情并处理它或完全终止线程。通过允许用户输入自定义方法(可能包含无限循环),您允许创建不考虑其运行线程中断状态的方法,这意味着没有配置 interrupt() 调用永远可以解决问题。

所有这一切都让人想起停机问题,因为您正试图与一个可能永远持续下去的子例程进行交互,而无需告诉外部例程任何新信息。我不确定它是否真的可以解决。

最简单的替代方法是(非正式地)要求用户输入的方法只对应于他们想要运行的任何循环的一个步骤。然后,您可以在步骤之间自行检查中断状态,我认为您当前的代码适用于此。

关于java - 需要帮助在自制仓鼠模拟器上实现启动/恢复/暂停/停止线程操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27670504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com