ExecutorCompletionService挂起

时间:2014-03-08 12:34:49

标签: java multithreading future hang callable

我在Java ExecutorCompletionService挂起程序完成时遇到了一些麻烦。

我需要使用ExecutorCompletionService而不是ExecutorService,因为在我的真实程序中,我想设置许多任务运行,并且只取第一个完成的结果。

可悲的是,我发现我的程序仍然挂起,即使所有任务都已处理完毕。

我创建了一个在运行时挂起的小例子。

import java.util.concurrent.*;

public class Debug {

    public static void main(String[] args) {
        CompletionService<String> compService = new ExecutorCompletionService<>(Executors.newFixedThreadPool(2));

        for (int i = 0; i < 2; i++) {
            compService.submit(new Task(i));
        }

        for (int i = 0; i < 2; i++) {
            try {
                String result = compService.take().get();
                System.out.println("RESULT: " + result);
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static class Task implements Callable<String> {

        private final int number;

        public Task(int number) {
            this.number = number;
        }

        @Override
        public String call() throws Exception {
            return "Number " + number;
        }
    }
}

如果有人能指出我做错了什么,我会非常感激!

感谢。

1 个答案:

答案 0 :(得分:4)

它只是因为你启动了一个执行程序,它继续运行(等待执行新任务),直到执行程序关闭,它才会启动执行程序:

    ExecutorService executor = Executors.newFixedThreadPool(2);
    CompletionService<String> compService = new ExecutorCompletionService<>(executor);

    for (int i = 0; i < 2; i++) {
        compService.submit(new Task(i));
    }

    for (int i = 0; i < 2; i++) {
        try {
            String result = compService.take().get();
            System.out.println("RESULT: " + result);
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    executor.shutdownNow();