In order to make full use of system resources, we usually do multi-threaded development. It is very simple to implement. When we need to use threads, we create a Thread (inherit Thread class, implement Runnable interface, use Callable and Future), but there are a few problems with this. If there are a large number of concurrent threads, it takes time and resources to create and destroy threads, and this is where thread pools come in handy

Java provides four thread pools via Executors, respectively

1.newSingleThreadExecutor()

Create a single threaded thread pool that uses only one worker thread to execute tasks, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority)

public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue())); }

2.newFixedThreadExecutor()

Create a fixed-length thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue

public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); }

3.newCachedThreadPool()

Create a cacheable thread pool, cache 60 seconds after execution if no thread is currently available, or remove thread if not called. Threads in the cache can be reused when the execute() method is called. An environment suitable for many short-term asynchronous tasks can improve program performance.

public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue()); }

4. NewScheduledThreadPool () (in ScheduleThreadPoolExecutor class, subclass ThreadPoolExecutor)

Create a fixed – length thread pool to support scheduled and periodic task execution

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue());
}
Copy the code

Before introducing the implementation mechanism of thread pools, let’s take a look at the important classes or interfaces of thread pools

ExecutorService is a true thread pool interface

Executors is a function of the Static factory that produces various types of thread pools

Executor is a top-level interface to the thread pool. It is only a tool for executing threads and provides only a execute(Runnable Command) method. The real thread pool interface is ExecutorService

AbstractExecutorService implements the ExecutorService interface, and implements most of these methods.

ThreadPoolExecutor, an AbstractExecutorService descendant, is the default implementation of ExecutorService