Java Wait until the threads (Threadpool) finish the work and begin another work

So, I create lets say 5 threads, and after completing their work, I would like to do another job. so how do you know when threads from an executor finish their work, and only after that they start the superload method?

Home:

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 something like executor.awaitTermination (60, TimeUnit.SECONDS); {doesn't work} or something that works

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

Grade:

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

}

+4
source share
1 answer

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 
+6
source

Source: https://habr.com/ru/post/1345725/


All Articles