The article directories

  • One, foreword
  • The differences between the use of thread pools and the four thread pools
    • 2.1 Use of thread pools
    • 2.2 Differences between the four thread pools
  • Third, the basic principle of thread pool
  • Fourth, the end

One, foreword

Project development, the need to use multithreading, we generally directly use the thread pool, rather than their own temporary creation of a new thread, the reason is that each creation and destruction of threads, for CPU and memory overhead is relatively large, affecting the stability and efficiency of the backend.

Multiple threads alone, to use multithreading to create more than a thread, this is a must, when the completion of multithreading, do not destroy the thread will occupy memory resources, destroy the thread behind the use of multithreading and new, unable to reuse before the thread.

Using the thread pool, according to the actual project, the new well specified number of threads in thread pool, need to use them, the use of don’t need to release it, already realized the purpose of multithreading, and can let the team code standardization, the most important thing is that the thread reuse can be implemented to reduce the cost of creating and destroying threads.

There are three ways to destroy a thread: Interrupt () stop() Run () logic completes execution

The differences between the use of thread pools and the four thread pools

2.1 Use of thread pools

The use of thread pool is to achieve multi-threaded concurrent functions, directly on the code:

package com.example.demo; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; // Each thread can only execute one task at a time. ExecutorService public class Main {public static void Main (String[] args) {// Fixed number of thread pools ExecutorService executorService = Executors.newFixedThreadPool(4);for (int i = 0; i < 10; i++) {
            executorService.execute(new Task());
        }
        executorService.shutdown();
    }

    static class Task implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "- Start the mission.");
            try {
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "- Execution completed"); }}}Copy the code

2.2 Differences between the four thread pools

Executors. NewFixedThreadPool () / / fixed number of threads in thread pool Executors. NewSingleThreadExecutor () / / only one thread thread pool Executors. NewCachedThreadPool () / / can be cached thread pool, in theory, the number of requests, The thread pool can create many threads to handle the Executors. NewScheduledThreadPool () / / provides according to the cycle of the Timer thread pool

   public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
Copy the code

The meaning of the five parameters: the initial number of threads, the maximum number of threads (capacity expansion), the initial number of threads and the maximum number of threads are the same, indicating no capacity expansion, thread lifetime, survival unit, blocking queue

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}
Copy the code

The initial number of threads and the maximum number of threads in a fixed pool are both 1 and block the queue

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}
Copy the code

The initial number of threads is 0 and the maximum number of threads (expanded) is Integer. In theory, the pool can create as many threads to handle as many requests

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    returnnew ScheduledThreadPoolExecutor(corePoolSize); } public ThreadPoolExecutor(int corePoolSize, int corePoolSize) Integer Maximum value long keepAliveTime, // 0 TimeUnit unit, // unit BlockingQueue<Runnable> workQueue) {this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }Copy the code
Public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, int keepAliveTime, TimeUnit unit, ThreadFactory ThreadFactory is a ThreadFactory used to create worker threads. RejectedExecutionHandler Handler) {reject execution policy default implementation (error), may not be RejectedExecutionHandlerCopy the code

Third, the basic principle of thread pool

Thread pooling is about thread reuse, which is achieved by building a blocking queue,

Understand blocking queues and thread pools: A blocking queue is essentially a task queue that holds multiple tasks; The thread pool holds the multiple threads, expands the blocking queue, and rejects the blocking queue.

In the thread pool, the thread executed by the run method is not destroyed, but blocked, and put into the blocking queue, and the next time to use the use of direct wake up, so as to achieve thread reuse.

The thread pool model can be understood as a simple producer-consumer model, but the consumer cannot block the producer. If the number of producers is too large, the consumer has two ways: expansion, reject processing, but cannot block the producer.

Reject strategy: directly report an error (default), discard the incoming task (tail removed), directly call task.run(), discard the task whose head waits the longest in the queue, add the current task to the blocking queue and store it, wait for Kong To retry (custom)

The only way to reuse a thread is if it never terminates. How do I get threads to perform new tasks? Thread communication via Shared memory (list.add) Thread is always running? When a task comes, execute it; Block when there are no tasks.

If the current number of tasks is too large, the number of tasks is added. If the peak value passes, the added threads are destroyed by setting the life cycle of the added threads.

Fourth, the end

The use and fundamentals of thread pools are analyzed.

Play code every day, progress every day!!