Java 在循环期间暂停
我正在运行一个 for 循环,并且在每次迭代时,我都会在后台执行一个 SwingWorker(持续大约 5 分钟)。 我有一个属性是同时在后台运行的Worker的数量。
for 循环有 100 次迭代,但我只想同时运行 5 个 SwingWorker。如果同时运行的工作线程数量超过 5,如何暂停循环迭代?当它变低时我怎样才能恢复它?
谢谢。
I am running a for loop and at each iteration, I execute a SwingWorker in background (who lasts around 5 minutes).
I have an attribute who is the number of Worker running in background at the same time.
The for loop has 100 iterations but I want only 5 simulutaneous SwingWorker running. How can I pause the loop iteration if the number of simulutaneous worker running if superior to 5 ? how can I resume it when it becomes lower ?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常我使用具有 5 个线程的 ExecutionService 来执行此操作。但你可以像这样使用信号量。
Normally I use an ExecutionService with 5 threads to do this. But you can use a Semaphore like this.
查看以下有关 SwingWorker 限制和监控的博客。它解释了如何定义 M 个并发线程来执行 N 个任务。
基本上,您必须创建一个线程池并让它管理工作人员的执行。
Check out the following blog about SwingWorker throttling and monitoring. It explains how to define a number M of simultaneous threads to execute N tasks.
Basically you'll have to create a threadpool and let that manage the execution of your workers.
http://blogs.oracle.com/swinger/entry/swingworker_throttling_and_monitoring
假设 for 循环除了执行 SwingWorkers 之外不执行任何操作,实现此目的的一种方法是将 100 个任务提交到 ThreadPoolExecutor,并将池大小设置为 5。
Assuming the for loop doesn't do anything other than execute your SwingWorkers, one way to do this is by just submitting 100 tasks to a ThreadPoolExecutor with the pool size set to 5.