代码之家  ›  专栏  ›  技术社区  ›  Yomal

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

  •  2
  • Yomal  · 技术社区  · 7 年前

    我正在制作一个新闻更新应用程序。为此,它需要能够在给定的时间段获得更新。在本文中,我创建了一个计时器,在给定的时间段内运行可调用的插件。这里我使用了一个FixedThreadPool(执行器)。 为此,我想知道future什么时候完成了它的工作,这样我就可以调用updateHeadlines方法。但当我使用完。get()它会阻塞gui。有没有一种方法可以在没有阻塞的情况下知道作业何时完成,以便我可以在完成后更新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();
            }
    3 回复  |  直到 7 年前
        1
  •  2
  •   erickson    7 年前

    不需要合并 Timer ExecutorService ,或使用回调。相反,计划a 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);
    }
    
        2
  •  2
  •   Raman Sharma    7 年前

    也许这对你有帮助 Callback with CompletableFuture

        3
  •  0
  •   michid    7 年前

    从Java 8开始,您可以使用 CompletableFuture 完成一次性任务时获取回调。在Java 8之前,你可以吃番石榴 ListenableFuture ,具有类似的功能。

    对于经常性任务,请使用 observable 模式,它与期货相对应,用于处理从周期性任务返回的多个项目。尽管如此,Java似乎并没有提供一个好的OOTB解决方案。