Android thread pool explain in simple terms (2)

Series Article Directory

The first chapter Android thread pool explain in simple language (1) The
second chapter Android thread pool explain in simple language (2)


Preface

In "Android Thread Pool Explained in Simple Terms (1)" , we have basically understood the advantages and disadvantages of threads and how to create them. According to different initialization parameters, configure the thread pool examples that are more suitable for the project. This chapter will explain in detail the related advancement of thread pools. Content, please read it carefully.


1. Thread creation strategy

The creation timing of threads in the thread pool is related to the corePoolSize and workQueue parameters, and it has its own certain logic rules.

Thread situation Strategy
The number of threads is less than corePoolSize Create new threads directly to handle new tasks
The number of threads is greater than or equal to corePoolSize, and the workQueue is not full Cache new tasks
The number of threads is greater than or equal to corePoolSize but less than maximumPoolSize, and the workQueue is full Create new threads to handle new tasks
The number of threads is greater than or equal to maximumPoolSize, and the workQueue is full Use rejection policy to process new tasks

The logic diagram of thread creation is as follows:
Insert picture description here

Two, thread resource recovery strategy

Considering that system resources are limited, the idle threads whose thread pool exceeds the corePoolSize number should be recycled. There is a problem with this operation, namely the timing of recycling. The current implementation is to recycle when the thread's idle time exceeds keepAliveTime.

Threads other than the number of core threads can be recycled, and idle threads in core threads can also be recycled. The premise of recycling is that the allowCoreThreadTimeOut attribute is set to true.

 public void allowCoreThreadTimeOut(boolean value) {
    
    
 	...
 }

Three, queuing strategy

As mentioned in the thread creation rule above, when the number of threads is greater than or equal to corePoolSize and the workQueue is not full, new tasks are cached. Here we need to consider what type of container to use to cache the new task. Through the introduction of the JDK document, we can know that there are 3 types of containers available for use, namely synchronous queues, bounded queues and unbounded queues. For tasks with priority, priority queues can also be added here.

For the four types of queues introduced above, the corresponding implementation classes are as follows:

Implementation class Types of Description
SynchronousQueue Synchronization queue The queue does not store elements, each insert operation must wait for another thread to call the remove operation, otherwise the insert operation will always be blocked
ArrayBlockingQueue Bounded queue Array-based blocking queue, sorting elements according to the FIFO principle
LinkedBlockingQueue Unbounded queue Based on the blocking queue of the linked list, the elements are sorted according to the FIFO principle
PriorityBlockingQueue Priority queue Priority blocking queue

Four, rejection strategy

As mentioned in the above thread creation rule strategy, when the number of threads is greater than or equal to maximumPoolSize, and the workQueue is full, or the current thread pool is closed, the rejection strategy is used to process new tasks.

Java thread pool provides 4 kinds of rejection strategy implementation classes, as follows:

Implementation class Description
AbortPolicy Discard the new task and throw a RejectedExecutionException
DiscardPolicy Do nothing, just discard the new task
DiscardOldestPolicy Discard the element at the top of the queue and execute a new task
CallerRunsPolicy The rejected task will be processed in the thread pool currently running in the thread pool. This strategy provides a simple feedback control mechanism that can slow down the submission of new tasks.

Among the above four rejection policies, AbortPolicy is the default policy used by the thread pool implementation class. We can also modify the rejection strategy of the thread pool through the following methods of ThreadPoolExecutor.

public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
    
    
	...
}

Five, how the thread is created

In the implementation of the thread pool, the creation of threads is accomplished through the implementation of the thread factory interface ThreadFactory. By default, a DefaultThreadFactory object of the implementation class of ThreadFactory will be returned.

   public static ThreadFactory defaultThreadFactory() {
    
    
        return new DefaultThreadFactory();
    }
    /**
     * The default thread factory
     */
    private static class DefaultThreadFactory implements ThreadFactory {
    
    
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
    
    
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }

		/**
		* 创建线程设置优先级和线程名
		*/
        public Thread newThread(Runnable r) {
    
    
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

Of course, we can also use the method setThreadFactory (ThreadFactory threadFactory), we can also set as a custom thread factory.

to sum up

。。。

Guess you like

Origin blog.csdn.net/luo_boke/article/details/108754669