user615927
user615927

Reputation: 153

Java Wait until threads(Threadpool) finish their work and start another work

So I create lets say 5 threads, and after their work is completed I'd like to do another work. so how to find out when threads from executor finish their work, and only then start superwork method?

Main:

 ExecutorService executor = Executors.newFixedThreadPool(5);
   CountDownLatch doneSignal = new CountDownLatch(5);//thread number
   for(int i=0;i<5;i++){

   getLogFile n = new getLogFile(doneSignal, i);// work method

   executor.execute(n);
   doneSignal.await();  
   }

//Probably here something like executor.awaitTermination(60,TimeUnit.SECONDS);{doesn't work} or something that works

Superworkmethod(uses thread created files);//main thread probably starts thi

Class:

public static class getLogFile implements Runnable {
 private final CountDownLatch doneSignal;
   private final int i;
   getLogFile(CountDownLatch doneSignal, int i) {
      this.doneSignal = doneSignal;
      this.i = i;
   }

    public int run1(String Filenamet) {
    //do work
    }
    public void run() {
            run1(file);
            doneSignal.countDown();
    }

}

Upvotes: 4

Views: 3616

Answers (1)

axtavt
axtavt

Reputation: 242686

You can use ExecutorService.invokeAll():

ExecutorService executor = Executors.newFixedThreadPool(5);

List<Callable<Object>> tasks = new ArrayList<Callable<Object>>();    
for(int i=0;i<5;i++){
    tasks.add(Executors.callable(new getLogFile(doneSignal, i)));
}

executor.invokeAll(tasks);
// Here tasks are completed

Upvotes: 6

Related Questions