Search code examples
javaloopsswingworker

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.


Solution

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