Create a thread pool through the standard library

The reason why the thread pool improves the efficiency of thread utilization

        The thread pool can improve the efficiency of our use of threads, which is much faster than the frequent creation and destruction of threads through the system

        We can create multiple threads in the thread pool first, take them out of the thread pool for use when we want to use them, and put them back into the thread pool for next use

        Why is it faster and more efficient for us to take threads from the pool than to create threads from the system?

        If you create a thread from the system, you need to call the system api, and then the operating system kernel completes the creation of the thread, but the kernel provides services for all processes, so when the kernel creates threads for you is uncontrollable

        If the thread is obtained from the thread pool, the above-mentioned operations in the kernel are all done in advance. Now the process of obtaining the thread is completely controlled by the user. When the user wants to obtain the thread, he can do whatever It can be obtained at any time and is controllable

Create threads through the factory class

        The concept of factory mode can be seen: Factory mode concept

        1. Example code for instantiating the thread pool

ExecutorService service1= Executors.newFixedThreadPool(4);   //创造一个固定线程数量的线程池
ExecutorService service2=Executors.newCachedThreadPool();   //创建一个线程动态变化的线程池
ExecutorService service3=Executors.newSingleThreadExecutor();   //创建单个线程(比原生的创建线程api更简单一点)
//类似于定时器的效果,添加一些任务,任务都在后续的莫个时刻再执行
//被执行的时候不是只有一个扫描线程来执行任务,可能是由多个线程共同执行所有的任务
ExecutorService service4=Executors.newScheduledThreadPool(4);

        2. Add the case code of the task to the thread pool

//循环1000次,通过submit向线程池中添加1000个任务,线程池中的线程会解决添加到线程中的任务
        for(int i=0;i<1000;i++){
            service1.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello");
                }
            });
        }

        The meaning of this code is to loop 1000 times, add 1000 tasks of printing "hello" to the thread pool through submit, and the threads in the thread pool will solve the tasks added to the thread.

        The thread pool object adds tasks to the thread pool by calling the submit method. The parameter of submit is an object of the Runnable type, and the added task content is specified by rewriting the run method in the object of the Runnable type.

Create a thread pool through the ThreadPoolExecutor class

        1. Introduction to the ThreadPoolExecutor class

        ThreadPoolExecutor is the most comprehensive class for creating thread pools. Executors factory classes create thread pools that further encapsulate ThreadPoolExecutor (ThreadPoolExecutor creates thread pools natively, while Executors are encapsulated)

        The number of threads in ThreadPoolExecutor is not fixed, but will change dynamically according to the current task (adaptive)

         2. Introduction to the parameters of the ThreadPoolExecutor class

        

ThreadPoolExecutor executor=new ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadfactory,RejectedExecutionHandle handler)

        1. corePoolSize number of core threads, at least these threads, even if your thread pool has no tasks at all

        2. maximumPoolSize is the maximum number of threads, which cannot exceed these threads at most, even if your thread pool is busy and smoking, it cannot be more than this number

        3. keepAliveTime allows the maximum time that the thread can be idle, and TimeUnit is the unit of this time value (for example, keepAliveTime is 3000, TimeUnit is ms, which means that non-core threads (extended threads) that have no tasks after 3000ms will be destroyed, guarantee Adaptive thread pool)

        4.workQueue represents a blocking queue that manages thread pool tasks. Tasks are added to the blocking queue workQueue, and threads go to the blocking queue to obtain tasks for execution.

        5. threadfactory represents the thread factory, which involves the factory mode, and creates threads through this factory class

        6. Handler indicates the rejection method/rejection strategy. There is a blocking queue in the thread pool. When the blocking queue is full, continue to add tasks. How to deal with it?

At present, the standard library has provided four strategies ( these four processing strategies are very important )

(1).ThreadPoolExecutor.AbortPolicy When the blocking queue in the thread pool is full and then add tasks, an exception will be thrown directly, and the thread pool will not work (equivalent to the newly added tasks will not be done, and there are no tasks in the blocking queue. Executed tasks will not be done)

(2).ThreadPoolExecutor.CallerRunsPolicy Whoever is the thread that adds this task will execute this task

(3).ThreadPoolExecutor.DiscardOldestPolicy discards the oldest tasks and adds new tasks

(4).ThreadPoolExecutor.DiscardPolicy discards new tasks

        

Guess you like

Origin blog.csdn.net/q322359/article/details/132021696