Vincent Roye
Vincent Roye

Reputation: 2841

Java pause during a loop

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.

Upvotes: 2

Views: 629

Answers (3)

mikera
mikera

Reputation: 106351

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.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

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();
     }
 }

Upvotes: 2

Mr_Dark
Mr_Dark

Reputation: 163

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

Upvotes: 1

Related Questions