在Java ScheduledExecutorService和FutureTask上寻求清晰度

时间:2009-07-24 19:18:17

标签: java multithreading futuretask

我刚刚开始研究Java中的Futures和ScheduledExecutorService,我想知道为什么我的Callable没有按照我指示的时间表运行。在这个示例代码中,可调用运行一次,但应用程序永远不会完成,任务也不会再次运行,这是我预期会发生的事情(我确定问题与我的期望有关)。

Runnables工作正常; Callables似乎永远阻止,但我不确定为什么......我错过了什么?

谢谢!

   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());

    }
}

1 个答案:

答案 0 :(得分:8)

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

在调用run FutureTask方法之后,后续调用会立即返回,而不会委派给任务的Callable实例。

只有Runnable可以用作重复任务,这不允许传回结果。相反,为Runnable任务提供一个可以在其run方法结束时调用的回调,以将每个任务执行的结果报告给其他线程中的侦听器。