In this Q&A, we'll go over how to execute tasks in a thread pool.
With ExecutorService implementations executing tasks in multiple threads is pretty straight forward. It involves
- creating a thread pool using Executors class
- shutdown the thread pool once task execution is complete and the thread pool is no longer needed
See sample code below
ExecutorService es = Executors.newFixedThreadPool(2); // create thread pool
// executes Runnable tasks
es.submit( () -> System.out.println(Thread.currentThread().getName()));
es.submit( () -> System.out.println(Thread.currentThread().getName()));
es.shutdown();
// waits for upto secs for threads in the pool to terminate
es.awaitTermination(1, TimeUnit.SECONDS);
System.out.println("end");
Comments
Post a Comment