有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    你的问题是:

    try {
        final Double sum = future.get();
        result.add(sum);
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
    

    当你点击cancel按钮时,它实际上会取消主任务DoWorkTask,这会中断执行主任务的线程,因为它正在等待future.get()的结果,一个InterruptedException会被触发,但在你当前的代码中,你会抛出一个RuntimeException,这样你的主任务就会立即退出,因此不能中断子任务,当抛出InterruptedException时,应该继续

    try {
        final Double sum = future.get();
        result.add(sum);
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        // log something here to indicate that the task has been interrupted.
    }