I need to execute some amount of tasks 4 at a time, something like this:
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
tas
Follow one of below approaches.
submit
on ExecutorService
and check the status with blocking call get()
on Future
object as suggested by Kiran
invokeAll()
on ExecutorServiceshutdown, awaitTermination, shutdownNow
APIs of ThreadPoolExecutor in proper sequence Related SE questions:
How is CountDownLatch used in Java Multithreading?
How to properly shutdown java ExecutorService
I've just written a sample program that solves your problem. There was no concise implementation given, so I'll add one. While you can use executor.shutdown()
and executor.awaitTermination()
, it is not the best practice as the time taken by different threads would be unpredictable.
ExecutorService es = Executors.newCachedThreadPool();
List<Callable<Integer>> tasks = new ArrayList<>();
for (int j = 1; j <= 10; j++) {
tasks.add(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int sum = 0;
System.out.println("Starting Thread "
+ Thread.currentThread().getId());
for (int i = 0; i < 1000000; i++) {
sum += i;
}
System.out.println("Stopping Thread "
+ Thread.currentThread().getId());
return sum;
}
});
}
try {
List<Future<Integer>> futures = es.invokeAll(tasks);
int flag = 0;
for (Future<Integer> f : futures) {
Integer res = f.get();
System.out.println("Sum: " + res);
if (!f.isDone())
flag = 1;
}
if (flag == 0)
System.out.println("SUCCESS");
else
System.out.println("FAILED");
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}