Java thread pool Detailed _JDK1.8.0_191

Java thread pool


The role of the thread pool

1. reuse existing threads, reduce thread creation when handling multiple requests, the destruction of expenses incurred.

2. When a request reaches worker usually already exist, without waiting for a request, improve the responsiveness of the system.


Executors static factory method thread pool

1.newFixedThreadPool

Create a fixed-size thread pool, whenever you submit a task to create a thread until it reaches the maximum length of the pool, then the length of the thread pool will remain no change.

2.newCachedThreadPool

Creates a cached thread pool, if the length of the current thread pool exceeds the need to deal with it the flexibility to recover idle thread, when demand increases, it may be the flexibility to add new thread.

3.newSingleThreadExecutor

Creating a single threaded executor, it only creates a unique worker thread to perform the task, executor will ensure that the sequence of tasks specified in accordance with the task queue (FIFO, LIFO, priorities) execution.

4.newScheduledThreadPool

Create a fixed-size thread pool, but also support the timing and periodicity of task execution, similar to the Timer.


ThreadPoolExecutor thread pool class constructor

/ ** 
 * Creates a thread pool by the given initialization parameters (ThreadPoolExecutor) 
 * 
 * @param core number of threads in the thread pool corePoolSize core thread will not be destroyed even if the free, 
* unless allowCoreThreadTimeOut been set
* @param maximumPoolSize thread pool the maximum number of threads allowed * @param keepAliveTime indicates the current time is greater than the number of threads core threads, before an idle thread is destroyed
* the maximum time to wait for the arrival of new tasks *
@param unit keepAliveTime parameters of time units * @param workQueue the task is executed the former is used to store the queue, the queue will only store the Runnable tasks submitted by the execute method * @param threadFactory Executor create a new thread factory used * @param Handler due to the number of threads and the queue is full, refused to execute the policy when blocked * @throws IllegalArgumentException if one of the following holds:<br> * {@code corePoolSize < 0}<br> * {@code keepAliveTime < 0}<br> * {@code maximumPoolSize <= 0}<br> * {@code maximumPoolSize < corePoolSize} * @throws NullPointerException if {@code workQueue} * or {@code threadFactory} or {@code handler} is null */ public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }

 Thread pool parameters

1. Core Threads: Number of threads even when idle will not be destroyed

2. The maximum number of threads: maximum number of threads allowed in the pool thread

3. Maintain survival time: idle threads waiting for new tasks before time is destroyed

4. The survival time units: latency unit

5. Work Queue: tasks to be stored in the queue

6. Thread Factory: Factory created a new thread

7. refused strategy: take the number of threads when the queue is full and deny policy


Work Queue

There are many job queue, but have achieved BlockQueue Interface

Queue Type Thread pool type Feature
LinkedBlockingQueue

FixedThreadPool

SingleThreadPool

Use job queue

Based on FIFO queue list
SynchronousQueue CachedThreadPool use the work queue Does not save the job submission, but directly create a thread to perform new tasks
DelayedWorkQueue ScheduledThreadPool use the work queue  

Rejection policy

1.AbortPolicy: discards the task and throw RejectedExecutionException exception.

2.CallerRunsPolicy: As long as the thread pool is not closed, the policy directly in the caller's thread, run the current task is discarded.

3.DiscardOldestPolicy: discard the oldest in the queue a task, the task is about to be executed, and try to submit the current job again.

4.DiscardPolicy: discard tasks, without any treatment.


 

 Task processing thread pool policy

Task processing thread pool as shown .

 

Logic more clear, in fact, this is a logical thread pool execute () method, the following look at the source code:

//通过execute向线程池提交任务
public
void execute(Runnable command) { if (command == null) throw new NullPointerException(); int c = ctl.get();
//如果当前线程数未达到核心线程数,则直接创建线程来执行新任务
if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return; c = ctl.get(); }
//否则将任务加入阻塞队列,这里进行双重检查,如果线程池已经关闭,则调用reject(),
//如果当前线程池线程数为0,则新建线程
if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); if (! isRunning(recheck) && remove(command)) reject(command); else if (workerCountOf(recheck) == 0) addWorker(null, false); }
//如果加入阻塞队列失败,则尝试新建一个线程,如果失败了
//则说明线程池关闭了或者线程达到最大线程数,因此调用reject()
else if (!addWorker(command, false)) reject(command); }

线程池提供了两个方法,用来关闭线程池。

(1)shutdown():不会立即关闭线程池,但也不接受新的任务,等待队列中所有任务执行完毕后关闭。

(2)shutdownNow():立即终止线程池,并尝试打断正在执行的任务,清空工作队列,返回尚未执行的任务。


线程池的线程数应该如何设置

Nthreads = Ncpu * (1 + w/c)  w为阻塞时间,c为计算时间

IO密集型:w/c>1,因此线程数应该为cpu的数倍,但需要考虑线程所占内存,因此通常将线程数设置为cpu的2倍。

CPU密集型:w/c=0,因此线程数为CPU个数。通常将线程数设置为CPU+1,防止线程由于偶尔出现的原因而暂停。

 

 

 

 


 

Guess you like

Origin www.cnblogs.com/yfzhou/p/11231336.html