Java任务什么都不做?

标签 java multithreading javafx task executorservice

我有一个程序,其中使用由 ExecutorService 控制的多个任务。我实际上使用了 Runnable,现在将其更改为任务,但是我似乎做错了一些事情,因为我的任务中应该发生的所有事情都没有发生。我应该提到,程序不会完成,它会无限运行。有人可以告诉我我错过了什么吗?

public class Test{
    ExecutorService exec;

    public Test (){
        exec = Executors.newCachedThreadPool();
        run();
    }

    public static void main(String[] args) {
        Test test = new Test();
    }

    private void run() {
        System.out.println("This works normal");
        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call(){
                System.out.println("Here nothing happens already");
                for (int i = 0; i < 10; i++)
                    exec.submit(() -> { System.out.println("Offcourse no sub-task works either"); });
                return null;
            }
        };
        exec.submit(task);
    }
}

这些是我的导入:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javafx.concurrent.Task;

I use:
- Netbeans IDE 8.2
- Java
- Windows 10 Pro

最佳答案

作为一个不寻常的功能,Task(属于 javafx 包的一部分)同时实现了 CallableRunnable。当您将任务提交给 ExecutorService 时,它会调用 Task.run 方法,该方法在 Task 中有一个空的、已 stub 的实现。如果您在匿名类中重写run,那么您将看到代码运行。

您是否考虑过直接从 Callable 创建一个匿名类?或者您是否因为使用 JavaFX 而有意使用 Task 类?

如果您正在使用 JavaFX 并有意使用 Task,则 Task API 会建议以下内容:

Although ExecutorService defines several methods which take a Runnable, you should generally limit yourself to using the execute method inherited from Executor.

Task API

call 方法通常适用于您使用 Service 的情况。

要关闭 ExecutorService,您应该调用 exec.shutdown()

关于Java任务什么都不做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49263258/

相关文章:

java - 如何从其他线程更改 UI

java - 无法更改parallelStream().forEach() 中的项目值?

java - 为简单的 java 项目选择什么原型(prototype)

java - 使用多个线程处理单个 HTTP 请求

Python:报纸模块——有什么方法可以直接从 URL 获取文章?

javafx - 尝试将 javafx WebView 渲染到离屏缓冲区或 FBO

spring - 如何在main函数中获取ApplicationContext - Spring boot

java - mapper.writeValue() 方法出错

java - Java 中的 Hibernate DetachedCriteria 多个结果

c# - ThreadPool RegisterWaitForSingleObject 的资源使用