Skip to content

Instantly share code, notes, and snippets.

@chathurangat
Created December 28, 2017 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chathurangat/f5cf0aae145ac86e37d6e1dda2efb617 to your computer and use it in GitHub Desktop.
Save chathurangat/f5cf0aae145ac86e37d6e1dda2efb617 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class Application {
public static void main(String[] args) throws InterruptedException {
System.out.println("main thread is started");
ExecutorService executorService = Executors.newCachedThreadPool();
CountDownLatch countDownLatch = new CountDownLatch(10);
List<Callable<String>> allCallableList = new ArrayList<>();
for (int taskIndex = 0; taskIndex < 10; taskIndex++) {
//creating the callable object
Callable<String> callable = () -> {
System.out.println("Thread [" + Thread.currentThread().getName() + "] is executing the task");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("sleeping thread get interrupted");
}
countDownLatch.countDown();
return "done";
};
allCallableList.add(callable);
}
//execute all the callables in background threads
executorService.invokeAll(allCallableList);
countDownLatch.await();
System.out.println("main thread completed ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment