what is Executors?
java
java.util.concurrent.Executors simplify concurrent programing by managing Thread objects for you. It allows you to manage the execition of asynchronous tasks without having to explicitly manage the lifecycle of threads.socket
public class CachedThreadPool { public static void main(String[] args) { ExecutorService pool = Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++) { pool.execute(new LiftOff()); } pool.shutdown(); } }
# shutdownasync
prevent new tasks from being submitted to that Executor.ui
current thread will continue to run all existing tasks.spa
public class FixedThreadPool { public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(5); for (int i = 0; i < 5; i++) { pool.execute(new LiftOff()); } pool.shutdown(); } }
# newFixedThreadPoolcode
use bounded number of threads.ci
we do EXPENSIVE thread allocation ONCE, up front.it
save time for systems such as event-driven ones which require threads that can be serviced ASAP.io
# newCachedThreadPool
event
create as many threads as it needs during the execution of a program.
a reasonable first choice as an Executor.
public class SingleThreadExecutor { public static void main(String[] args) { ExecutorService pool = Executors.newSingleThreadExecutor(); for (int i = 0; i < 5; i++) { pool.execute(new LiftOff()); } pool.shutdown(); } }
# newSingleThreadExecutor
useful if you want to run a task continually(long-lived task, eg: listening to incoming socket connection).
if > 1 task is submitted to s SingleThreadExecutor, they will be queued, all using the smae thread.