我正在制作一个新闻更新应用程序。为此,它需要能够获取给定时间段的更新。在此我创建了一个计时器来在给定的时间段运行可调用插件。这里我使用了FixedThreadPool(执行器)。 为此,我想要知道 future 何时完成其工作,以便我可以调用 updateHeadlines 方法。但是当我使用 finish.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();
}
最佳答案
应该不需要结合Timer
和ExecutorService
,或者使用回调。相反,安排一个调用插件的 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 - java中如何知道线程池的任务何时结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46940394/