Java 按两次ToggleButton(仅第一次有效)时,无法在自定义线程中执行while循环
按照我的程序的工作方式,按下按钮时会调用一个方法。然后,我有一个新线程,它有一个while循环,每隔指定的时间调用另一个方法,直到再次按下togglebutton。我该如何编写这样的程序?我尝试了Thread.wait(),但它会导致GUI更新出现问题Java 按两次ToggleButton(仅第一次有效)时,无法在自定义线程中执行while循环,java,javafx,fxml,Java,Javafx,Fxml,按照我的程序的工作方式,按下按钮时会调用一个方法。然后,我有一个新线程,它有一个while循环,每隔指定的时间调用另一个方法,直到再次按下togglebutton。我该如何编写这样的程序?我尝试了Thread.wait(),但它会导致GUI更新出现问题 解决了。谢谢大家! 您可以尝试将线程对象保存到全局变量,并在再次按下切换按钮时停止该对象 在线程上使用wait方法将不起作用,因为wait的工作方式与预期不同(请参阅) 第二个问题(IllegalStateException:不在FX应用程序线程
解决了。谢谢大家! 您可以尝试将
线程
对象保存到全局变量,并在再次按下切换按钮
时停止该对象
在线程上使用wait
方法将不起作用,因为wait
的工作方式与预期不同(请参阅)
第二个问题(IllegalStateException:不在FX应用程序线程上)可能是由方法performAction(ActionEvent)
引起的,因为它试图更改GUI中的内容,而这是不允许从应用程序线程以外的其他线程进行的。要避免这种情况,可以使用Platform.runLater(Runnable)
(请参阅或)
解决方案可能如下所示:
private Thread thread;
//call this method every time the toggle button is pressed
private void play(final ActionEvent ae) {
if (thread == null) {
//start in a new thread
thread = new Thread(new Runnable() {//better add a runnable to the new Thread than overwriting the run method of Thread
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {//run until the thread is interrupted
try {
Thread.sleep(speed);
//run this in platform to avoid the IllegalStateException that no fx thread is used
Plaform.runLater(() -> performAction(ae));
}
catch (InterruptedException e) {
//e.printStackTrace();
//set the interrupted flag again (was unset when exception was caught)
Thread.currentThread().interrupt();
}
}
}
});
thread.start();
}
else {
//stop the current thread
thread.interrupt();
thread = null;
}
}
如果您的定期任务简单且快速,则使用(例如)。否则,如果是定期后台任务,请参阅。