我只是开始研究Java中的Futures和ScheduledExecutorService,我想知道为什么Callable不在我指定的时间表上运行。在此示例代码中,可调用对象仅运行一次,但应用程序永远不会完成,任务也不会再次运行,这正是我期望发生的事情(我确定问题出在我的期望之内)。

可运行物品运行良好;可调用对象似乎会永远阻止,但我不确定为什么。...我想念的是什么?

谢谢!

   public class ExecutorExample {

    /**
     * @param args
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException, ExecutionException {

        ScheduledExecutorService scheduler =  Executors.newScheduledThreadPool(5);

        FutureTask<ArrayList<String>> ft1 = new FutureTask<ArrayList<String>>(new Callable<ArrayList<String>>(){
            @Override
            public ArrayList<String> call() {
                ArrayList<String> stuff = new ArrayList<String>();
                for(int i = 0;i<10;i++){
                    String thing ="Adding " + i + " to result";
                    stuff.add(thing);
                    System.out.println(thing);

                }
                return stuff;
            }});

        scheduler.scheduleAtFixedRate(ft1, 0, 1, TimeUnit.SECONDS);

        System.out.println(ft1.get());
        System.out.println(ft1.isDone());

    }
}

最佳答案

问题在于使用了FutureTask,并且如其类文档所述,“一旦计算完成,就无法重新开始或取消计算。”

一次调用runFutureTask方法后,随后的调用将立即返回,而不会委托(delegate)给该任务的Callable实例。

只能将Runnable用作重复任务,并且这不允许传递结果。相反,给Runnable任务一个回调,可以在其run方法的末尾调用该回调,以将任务每次执行的结果报告给其他线程中的监听器。

10-02 04:26
查看更多