Skip to content

Instantly share code, notes, and snippets.

@wkdalsgh192
Last active July 12, 2021 12:29
Show Gist options
  • Save wkdalsgh192/844dbc3ecf9b0bd5ce7f596c08ca89eb to your computer and use it in GitHub Desktop.
Save wkdalsgh192/844dbc3ecf9b0bd5ce7f596c08ca89eb to your computer and use it in GitHub Desktop.
// new single thread created and managed by executor service
ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable<String> hello = () -> {
Thread.sleep(2000L);
return "Hello";
};
Future<String> submit = executorService.submit(hello); // callable object executed and falls asleep for 2 sec
System.out.println(submit.isDone()); // main thread keep running - 1
System.out.println("Started"); // - 2
submit.get(); // To get the result, it joins the main thread - 3
System.out.println(submit.isDone()); // once done, the main thread operates the remaining tasks - 4
System.out.println("End!!");
executorService.shutdown(); // executors should be shut down manually, otherwise it keeps waiting for another task forever,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment