java ScheduledExecutorService中是否有取消任务的选项?
我正在javaFX上编写一个应用程序,作为我的视图(在MVVM体系结构中)的一部分,我使用FXML标签为客户端显示我的应用程序的状态(例如:是否成功上传了文件)
我想在更新几秒钟后清理这个状态标签
我使用这段代码来运行一个线程来执行此操作,但当上一个线程在完成其工作之前进行了多个更新时,就会出现问题
我想在执行新线程之前取消线程池中以前的任何线程,但我没有找到这样做的方法
public class MainWindowController implements Observer {
ViewModel vm;
ScheduledExecutorService scheduledExecutorService;
Stage stage;
@FXML
Label appStatus;
public void loadProperties(){
FileChooser fc = new FileChooser();
fc.setTitle("Load Project Properties");
fc.setInitialDirectory(new File("./resources"));
FileChooser.ExtensionFilter extensionFilter = new FileChooser.ExtensionFilter(
"XML Files (*.xml)", "*.xml");
fc.getExtensionFilters().add(extensionFilter);
File chosenFile = fc.showOpenDialog(stage);
//CONTINUE HERE
if(chosenFile==null){
appStatus.setTextFill(Color.RED);
vm.appStat.setValue("Failed to load resource");
}
else{
vm.setAppProperties(chosenFile.getAbsolutePath());
}
cleanStatusBox();
}
public void cleanStatusBox(){
scheduledExecutorService.schedule(new Runnable() {
@Override
public void run() {
Platform.runLater(()->vm.appStat.setValue(""));
}
},10000, TimeUnit.MILLISECONDS);
}
public void setViewModel(ViewModel vm) {
this.vm = vm;
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
appStatus.textProperty().bind(vm.appStat);
}
}
# 1 楼答案
一个
ScheduledExecutorService
(并且通常使用后台线程)的方法对于这一点来说过于苛刻取而代之的是,考虑使用一个^ {CD2>},一旦启动,将在指定的时间后在JavaFX应用程序线程上执行其^ {CD3>}处理程序。
playFromStart()
方法“重新启动”暂停,允许在没有冲突的情况下进行多次更新