java正确取消启动ExecutorService的JavaFX任务
我正试图编写一个GUI应用程序来执行许多计算密集型任务。因为这些任务需要一些时间,所以我希望使用ExecutorService
在多个线程上运行它们。但是,等待这些任务完成会冻结UI,因此我将其作为自身线程中的Task
运行,这会根据ExecuterService
的进度更新UI。用户使用Start
按钮启动任务,并且应该能够使用Cancel
取消任务
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ExecutionException;
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.scene.layout.HBox;
import javafx.scene.control.Button;
import javafx.scene.Scene;
import javafx.stage.Stage;
class DoWorkTask extends Task<List<Double>> {
// List of tasks to do in parallel
private final List<Callable<Double>> tasks;
// Initialize the tasks
public DoWorkTask(final int numTasks) {
this.tasks = new ArrayList<>();
for (int i = 0; i < numTasks; ++i) {
final int num = i;
final Callable<Double> task = () -> {
System.out.println("task " + num + " started");
return longFunction();
};
this.tasks.add(task);
}
}
@Override
protected List<Double> call() {
final ExecutorService executor = Executors.newFixedThreadPool(4);
// Submit all tasks to the ExecutorService
final List<Future<Double>> futures = new ArrayList<>();
this.tasks.forEach(task -> futures.add(executor.submit(task)));
final List<Double> result = new ArrayList<>();
// Calling task.cancel() breaks out of this
// function without completing the loop
for (int i = 0; i < futures.size(); ++i) {
System.out.println("Checking future " + i);
final Future<Double> future = futures.get(i);
if (this.isCancelled()) {
// This code is never run
System.out.println("Cancelling future " + i);
future.cancel(false);
} else {
try {
final Double sum = future.get();
result.add(sum);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
}
executor.shutdown();
return result;
}
// Some computationally intensive function
private static Double longFunction() {
double sum = 0;
for (int i = 0; i < 10000000; ++i) {
sum += Math.sqrt(i);
}
return sum;
}
}
public class Example extends Application {
final Button btnStart = new Button("Start");
final Button btnCancel = new Button("Cancel");
final HBox box = new HBox(10, btnStart, btnCancel);
final Scene scene = new Scene(box);
@Override
public void start(final Stage stage) {
box.setPadding(new Insets(10));
btnStart.setOnAction(event -> {
final DoWorkTask task = new DoWorkTask(100);
btnCancel.setOnAction(e -> task.cancel());
task.setOnSucceeded(e -> System.out.println("Succeeded"));
task.setOnCancelled(e -> System.out.println("Cancelled"));
task.setOnFailed(e -> {
System.out.println("Failed");
throw new RuntimeException(task.getException());
});
new Thread(task).start();
});
stage.setScene(scene);
stage.show();
}
}
但是,在启动任务并按下Cancel
按钮后,call()
函数似乎立即结束,而不会对未来的其余部分进行迭代。一些示例输出
task 0 started
task 1 started
task 2 started
Checking future 0
task 3 started
Checking future 1
task 4 started
Checking future 2
task 5 started
Cancelled
// Should continue to print Checking future x and
// Cancelling future x, but doesn't
task 6 started
task 7 started
task 8 started
task 9 started
...
剩下的期货没有一个被取消,看起来它们甚至没有被重复;call()
函数立即结束。当可调用项不是在ExecutorService
内运行,而是在DoWorkTask
内按顺序运行时,不会发生此问题。我相当困惑
# 1 楼答案
你的问题是:
当你点击cancel按钮时,它实际上会取消主任务
DoWorkTask
,这会中断执行主任务的线程,因为它正在等待future.get()
的结果,一个InterruptedException
会被触发,但在你当前的代码中,你会抛出一个RuntimeException
,这样你的主任务就会立即退出,因此不能中断子任务,当抛出InterruptedException
时,应该继续