Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
正确取消启动ExecutorService的JavaFX任务_Java_Multithreading_Javafx - Fatal编程技术网

正确取消启动ExecutorService的JavaFX任务

正确取消启动ExecutorService的JavaFX任务,java,multithreading,javafx,Java,Multithreading,Javafx,我正试图编写一个GUI应用程序来执行许多计算密集型任务。由于这些任务需要一些时间,我希望使用ExecutorService在多个线程上运行它们。但是,等待这些任务完成会冻结UI,因此我将其作为任务在自己的线程中运行,这会根据ExecuterService的进度更新UI。用户使用Start按钮启动任务,并且应该能够使用cancel取消任务 import java.util.ArrayList; import java.util.List; import java.util.concurrent.C

我正试图编写一个GUI应用程序来执行许多计算密集型任务。由于这些任务需要一些时间,我希望使用
ExecutorService
在多个线程上运行它们。但是,等待这些任务完成会冻结UI,因此我将其作为
任务
在自己的线程中运行,这会根据
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();
    }
}
剩下的期货没有一个被取消,看起来它们甚至没有被重复;
call()
函数立即结束。当可调用项不是在
ExecutorService
中运行,而是在
DoWorkTask
中按顺序运行时,不会发生此问题。我很困惑。

你的问题是:

try {
    final Double sum = future.get();
    result.add(sum);
} catch (InterruptedException | ExecutionException e) {
    throw new RuntimeException(e);
}
当您单击“取消”按钮时,它实际上会取消主任务
DoWorkTask
,这会中断执行主任务的线程,因为它正在使用
future.get()等待结果,引发了一个
中断异常
,但是对于当前代码,您会抛出一个
运行时异常
,这样您的主任务会立即退出,因此无法中断子任务,您应该在抛出
中断异常
时继续

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.
}

谢谢你,好先生。我以前不太了解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.
}