我有一个程序,其中使用由 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 包的一部分)同时实现了 Callable
和 Runnable
。当您将任务提交给 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.
call
方法通常适用于您使用 Service 的情况。
要关闭 ExecutorService
,您应该调用 exec.shutdown()
。
关于Java任务什么都不做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49263258/