java 如何知道线程池的任务何时结束

How to know when the tasks of threadpool is over in java

我正在制作一个新闻更新应用。为此,它需要能够在给定的时间段内获得更新。在这里,我创建了一个计时器,以 运行 给定时间段的可调用插件。这里我使用了 FixedThreadPool(executor)。 为此,我想知道未来什么时候完成它的工作,这样我就可以调用 updateHeadlines 方法。但是当我使用 finished.get() 时,它会阻止图形用户界面。有没有一种方法可以在不阻塞的情况下知道作业何时完成,然后我可以更新 GUI。

for (Callable curplugin : plugin) {
            new Timer(((NewsPlugin) curplugin).getUpdateFrequency(), new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Future<?> finished = executor.submit(curplugin);

                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {   
                            try {
                                ArrayList<Headline> news = (ArrayList) finished.get();
                                updateHeadlines();
                            } catch (InterruptedException ex) {
                                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (ExecutionException ex) {
                                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    });
                }
            }).start();
        }

如果您正在使用Java 8. 有一个可完成的未来,您可以在其中注册一个回调,当任务完成时将调用该回调。我想这会对你有所帮助。

也许这会对你有所帮助

不需要组合 TimerExecutorService,也不需要使用回调。相反,调度一个调用插件的 Runnable,并调度一个 invokeLater 来显示结果:

for (NewsPlugin plugin : plugins) {
  Runnable task = () -> {
    List<Headline> news;
    try {
      news = plugin.call(); /* There's really no need for plugin to be `Callable` */
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    java.awt.EventQueue.invokeLater(this::updateHeadlines);
  };
  int period = plugin.getUpdateFrequency();
  executor.scheduleAtFixedRate(task, period, period, TimeUnit.MILLISECONDS);
}

从 Java 8 开始,您可以使用 CompletableFuture 在一次性任务完成时获得回调。在 Java 8 之前,您可以使用 Guava 的 ListenableFuture,它具有类似的功能。

对于周期性任务,使用 observable 模式,它与 futures 对应,用于处理从周期性任务返回的多个项目。 Java 这里似乎没有提供好的 OOTB 解决方案。