Private project practice sharing thread pool of Java Multithread downloader project instance

Link can 2022-01-26 14:59:11 阅读数:668

private project practice sharing thread

Introduction to thread pool

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 .

1. ThreadPoolExecutor Constructor parameter

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

2.  Thread pool working process

# Share the actual operation of private items #Java Thread pool of multithreaded downloader project instance _Java Project instance

3.  The state of the thread pool

There is... In the thread pool 5 Status , Namely :


The state after creating the thread pool is RUNNING


In this state , The thread pool will not receive new tasks , But it handles the remaining tasks in the blocking queue , Relatively mild .


In this state, the task being executed will be interrupted , And discard the blocking Queue task , Relative violence .


All the tasks have been executed , The active thread is 0 Coming to an end


Thread pool termination

4.  Thread pool closure

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 .

5.  Work queue

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.