Thread pooling: Avoids resource depletion of thread creation and thread destruction.

Executors provides four thread pools:

  • NewCachedThreadPool: Cache thread pool. If the length of the thread pool exceeds the processing requirement, idle threads can be reclaimed. If none are reclaimed, new threads can be created.
  • NewFixedThreadPool: a fixed-length thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.
  • NewScheduledThreadPool: Scheduled thread pool that supports scheduled and periodic task execution.
  • NewSingleThreadExecutor: single-threaded thread pool that uses a unique thread to execute tasks, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).

Let’s take a look at the following attributes required for a thread pool:

PoolSize: specifies the number of threads in which the program is currently running.

CoreSize: number of core threads.

MaximumPoolSize: specifies the maximum number of threads in the thread pool.

KeepAliveTime: the thread exits due to timeout if the idle time expires.

BlockingQueue: Sets a block for waiting tasks to be executed.

(Thread-safe: ensure that only one element can be fetched from the queue, and that no header element can be fetched from the queue, and that no header element can be added to the queue when it is full.)

Thread pool running flow:

When a task needs to be performed:

Poolsize < coresize -> starts a new thread execution

The poolsize = coresize && queue is not full -> The number of core threads has been reached.

Poolsize < MaximumPoolSize && queue full -> create a new thread.

(Usually out-of-core threads are “borrowed,” meaning out-of-core threads are a predictable exception and don’t happen very often (if they do, I think you should adjust your core thread count).

Poolsize = MaximumPoolSize && Queue full -> All options are exhausted and RejectedExecutionHandler will reject the new task according to saturation policy.

If keepAliveTime is set, you can use the following configuration to determine whether timeout processing is enabled when the value is smaller than corePoolSize.

However, when MaximumPoolSize is exceeded, a timeout must occur because these threads are not normal.

**allowCoreThreadTimeOut: ** Whether to allow the core thread to exit due to timeout.

If this value is false(the default) and poolSize<=corePoolSize, the thread pool guarantees that the core threads are alive and will not timeout out. (So as long as the corePoolSize is not exceeded, the thread is idle instead of being destroyed)

If true, the timeout exit is allowed regardless of poolSize.

If poolSize>corePoolSize, this parameter, whether true or false, allows timeout.

)

(So roughly the flow: Execute a task, start a new thread if the number of threads is less than coresize, and queue it if it is equal to coresize. If the queue is full, a new thread is started. If the thread is equal to the maximum thread, execute the saturation policy reject task.

Custom thread: can be found, in fact, we said that a few parameters, very simple. public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) /** * Coresieze is the same as maximumPool, so that's why it's fixed size. And blocking LinkedBlockingQueue has no initial size and is an unbounded queue. So tasks that come in, if there aren't enough threads, they all queue up and wait. KeepAliveTime: 0. By default, timeout is enabled only when the maximum number of threads is exceeded. */ public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); ExecutorService newSingleThreadExecutor() {return new. ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); } /** * The core thread is 0 and the maximum number of threads is infinite. This means that all threads have keepalivetime and have a short lifetime. (Caching threads means that executing threads are cached for a certain amount of time and then released.) It is very easy to run out of memory when using such an infinite pool of threads. That's why Ali doesn't recommend using Executors to create thread pools. In fact, custom thread pool is very useful, and you will be very clear. SynchronousQueue A blocking queue that does not store elements, in which each insert operation must wait until another thread calls a remove operation (i.e., each task must be taken over by another thread). */ public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {  return new ScheduledThreadPoolExecutor(corePoolSize); } public static ScheduledExecutorService newSingleThreadScheduledExecutor() { return new DelegatedScheduledExecutorService (new ScheduledThreadPoolExecutor(1)); Executorservice.execute (Runnable) or executorService.submit(Callable)Copy the code

A Thread is a Thread and a task is a task Runnable.

Creating a Runnable just implements the run method, which is a task, not a thread. It can’t execute, so it needs to be passed into Thread and executed.

The only way to start a Thread is through the start() instance method of the Thread class.

)

Thread pool rejection policy:

When the thread pool is full and the queue is full, a rejection policy needs to be implemented. The default policy does not feel good and will report an abnormal stop if it is full.

AbortPolicy (default)

Default policy, directly run out of exceptions to prevent the normal operation of the system

CallerRunsPolicy

Caller-run is a mediation mechanism that does not discard the task or throw an exception, but instead returns the task to the caller, such as the main thread

DiscardOldestPolicy

Discard the longest waiting task in the queue, and then queue the current task to try to submit the current task again

DiscardPolicy

The task is discarded without any processing or exception if the task is allowed to be lost

The new public number will be regularly updated later. Come and watch the ducks!