2

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.

3 Answers 3

2

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();
     }
 }
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.