Java Executors在任务完成之前退出

时间:2015-09-08 13:59:16

标签: java parallel-processing executorservice hazelcast

        public class MyCallable implements Callable<Boolean> {        
            @Override
            public Boolean call() {
              while(true){
                 try{
                  [... stuff]
                 }catch(Exception e){
                   System.out.println("Error!");
                 }
              }
            }
        }

    public static void main(String[] args) throws Exception {
                int parallelCallables = 6;        
                ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                        .setNameFormat("Grabber-thread-%d").build();
                facebookInfoGrabberExecutor = Executors.newFixedThreadPool(parallelCallables, namedThreadFactory);
                List<Future<Boolean>> futures = facebookInfoGrabberExecutor.invokeAll(tasks);
                System.out.println("unreachable");
    }

尽管看起来似乎不可能,我的程序可以打印“无法访问”。 当它到达那一行时,所有进程都处于WAIT状态。 我使用hazelcast,这可能是罪魁祸首,我仍然不知道。

1 个答案:

答案 0 :(得分:1)

您需要关闭Executor才能完成所有任务。

    int parallelCallables = 6;
    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("Grabber-thread-%d").build();
    ExecutorService facebookInfoGrabberExecutor = Executors.newFixedThreadPool(parallelCallables, namedThreadFactory);
    List<Future<Boolean>> futures = facebookInfoGrabberExecutor.invokeAll(tasks);
    // Add this!!!
    facebookInfoGrabberExecutor.shutdown();
    while (!facebookInfoGrabberExecutor.awaitTermination(1, TimeUnit.MINUTES)) {
        System.out.println("Waiting");
    }
    System.out.println("All done.");