Link can 2022-01-26 14:59:11 阅读数:668
Threads are creating , Some resources will be consumed in the process of destruction , To save these expenses ,jdk Added thread pool . Thread pooling saves overhead , Improve the efficiency of thread use . Alibaba development documents suggest using thread pool when writing multithreaded programs .
stay juc The package provides ThreadPoolExecutor class , This class can be used to create thread pools , This class has 4 An overloaded constructor , The core construction method is 7 A formal parameter , The meanings of these parameters are as follows :
· corePoolSize
Number of core threads in the thread pool
· maximumPoolSize
The maximum number of threads in the thread pool , Is the sum of the number of core threads and the number of non core threads
· keepAliveTime
The idle lifetime of non core threads
· unit
keepAliveTime A unit of time to live
· workQueue
When there are no idle threads , New tasks will be added to workQueue Waiting in line
· threadFactory
Thread factory , Used to create threads
· handler
Refusal strategy , Rejection policy when there are too many tasks to handle
There is... In the thread pool 5 Status , Namely :
· RUNNING
The state after creating the thread pool is RUNNING
· SHUTDOWN
In this state , The thread pool will not receive new tasks , But it handles the remaining tasks in the blocking queue , Relatively mild .
· STOP
In this state, the task being executed will be interrupted , And discard the blocking Queue task , Relative violence .
· TIDYING
All the tasks have been executed , The active thread is 0 Coming to an end
· TERMINATED
Thread pool termination
After the thread pool is used, it needs to be closed , The following two methods are provided for closing
· shutdown()
After the method is executed , The thread pool state changes to SHUTDOWN, No new missions , But it will complete the submitted tasks , This method does not block the execution of the calling thread .
· shutdownNow()
After the method is executed , The thread pool state changes to STOP, No new missions , The task in the queue is returned , And use interrupt To interrupt a task in progress .
jdk Some work queues provided in workQueue
· SynchronousQueue
Direct submission queue
· ArrayBlockingQueue
Bounded queues , Capacity can be specified
· LinkedBlockingDeque
Unbounded queue
· PriorityBlockingQueue
Priority task queue , Tasks can be executed according to their priority
copyright:author[Link can],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/01/202201261459072217.html