我正在进行基本的Java FX任务练习。它在线程上的计数从1到150。当前值显示在标签上,并更新进度条。
有一个按钮可以启动任务,取消任务以及查看任务的取消状态。
让我感到困惑的是,为什么我一旦取消线程后就无法重新运行任务(如果我让任务完成,也会发生同样的事情)。
我希望能够重新运行任务。然后,我需要使其恢复运行(尽管在弄清楚如何重新运行任务后应该不那么困难)
来源 ;
public class JavaFX_Task extends Application {
@Override
public void start(Stage primaryStage) {
final Task task;
task = new Task<Void>() {
@Override
protected Void call() throws Exception {
int max = 150;
for (int i = 1; i <= max; i++) {
if (isCancelled()) {
break;
}
updateProgress(i, max);
updateMessage(String.valueOf(i));
Thread.sleep(100);
}
return null;
}
};
ProgressBar progressBar = new ProgressBar();
progressBar.setProgress(0);
progressBar.progressProperty().bind(task.progressProperty());
Label labelCount = new Label();
labelCount.textProperty().bind(task.messageProperty());
final Label labelState = new Label();
Button btnStart = new Button("Start Task");
btnStart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
new Thread(task).start();
}
});
Button btnCancel = new Button("Cancel Task");
btnCancel.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
task.cancel();
}
});
Button btnReadTaskState = new Button("Read Task State");
btnReadTaskState.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
labelState.setText(task.getState().toString());
}
});
VBox vBox = new VBox();
vBox.setPadding(new Insets(5, 5, 5, 5));
vBox.setSpacing(5);
vBox.getChildren().addAll(
progressBar,
labelCount,
btnStart,
btnCancel,
btnReadTaskState,
labelState);
StackPane root = new StackPane();
root.getChildren().add(vBox);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("java-buddy.blogspot.com");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
最佳答案
Task
documentation对此很清楚。
As with
FutureTask
, aTask
is a one-shot class and cannot be reused. SeeService
for a reusableWorker
.
服务文档中有一个可重新启动的并发服务示例。
关于multithreading - JavaFX任务一旦取消就不会重新运行,也不会一次完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23521672/