what is Executors?
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.
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();
}
}
# shutdown
prevent new tasks from being submitted to that Executor.
current thread will continue to run all existing tasks.
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();
}
}
# newFixedThreadPool
use bounded number of threads.
we do EXPENSIVE thread allocation ONCE, up front.
save time for systems such as event-driven ones which require threads that can be serviced ASAP.
# newCachedThreadPool
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.