Java 在循环期间暂停

发布于 2024-12-26 02:20:33 字数 195 浏览 0 评论 0原文

我正在运行一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

就此别过 2025-01-02 02:20:34

通常我使用具有 5 个线程的 ExecutionService 来执行此操作。但你可以像这样使用信号量。

 final Semaphore permits = new Semaphore(5);
 for(int i=0;i<100;i++) {
     permits.acquire();
     // add a task
 }



 // in the SwingWorker
 public String doInBackground() {
     try {
        return findTheMeaningOfLife();
     } finally {
        permits.release();
     }
 }

Normally I use an ExecutionService with 5 threads to do this. But you can use a Semaphore like this.

 final Semaphore permits = new Semaphore(5);
 for(int i=0;i<100;i++) {
     permits.acquire();
     // add a task
 }



 // in the SwingWorker
 public String doInBackground() {
     try {
        return findTheMeaningOfLife();
     } finally {
        permits.release();
     }
 }
几度春秋 2025-01-02 02:20:34

查看以下有关 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

动次打次papapa 2025-01-02 02:20:34

假设 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文