ExecutorService,如何知道所有线程何时完成而不阻塞主线程? [英] ExecutorService, how to know when all threads finished without blocking the main thread?

查看:713
本文介绍了ExecutorService,如何知道所有线程何时完成而不阻塞主线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多线程实现,我在其中创建一个ExecutorService并提交要执行的任务,我想知道所有线程被提交的时间已经完成而没有阻塞主线程和UI。我已经尝试过 ExecutorService.awaitTermination()但它阻止了主线程和UI。我搜索了很多,但我似乎无法找到一种优雅的方式来做到这一点。我正在考虑创建另一个线程来计算完成的线程数量,并在它们全部完成时启动一个事件,但这不是一个好方法,我想要一个更好的解决方案!

I have a multithreaded implementation where i create an ExecutorService and submit tasks to be executed, i want to know when all the threads is submited have finished without blocking the main thread and the UI. I've tried ExecutorService.awaitTermination() but it blocks the main thread and the UI. I've searched alot but i can't seem to find an elegant way of doing this. I'm currently thinking about creating another thread that counts the amount of threads finished and launches an event when they all finished, but that doesn't to be a good approach and i wanted a better solution!

推荐答案

使用 SwingWorker 关闭线程池并调用 awaitTermination()。这将阻止UI阻止并从SwingWorker实现上的事件调度线程调用 done(),您可以使用它来触发所需的任何UI更改。

Use a SwingWorker to shutdown the thread pool and call awaitTermination(). This will prevent the UI from blocking and call done() from the Event Dispatch Thread on your SwingWorker implementation which you can use to trigger the whatever UI changes you need.

如果您希望跟踪通过UI更新运行的线程,您可以使用工作线程在循环中监视它并调用 publish() 带有参数,然后传递给EDT上的 process()的实现。

If you desire to keep track of the threads running via a UI update you can use the the worker thread to monitor this in a loop and call publish() with arguments which then get passed to your implementation of process() on the EDT.

这篇关于ExecutorService,如何知道所有线程何时完成而不阻塞主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆