Reference: http://blog.csdn.net/suifeng3051/article/details/49444177
There are two thread pool classes in Java, namely: Threadpoolexecutor and Scheduledthreadpoolexecutor, all of which inherit from Executorservice. With these two classes, you can create a variety of different Java thread pools, and for the sake of creating a thread pool, the Java API provides the Executors factory class to help us create a wide variety of thread pooling. Let's take a look at these three classes separately.
Java thread pool Executorservice inheritance tree:
First, Threadpoolexecutor
Threadpoolexecutor is an implementation class for Executorservice and is also the most commonly used thread pool class in Java. The Threadpoolexecutor internally maintains a thread pool that can perform a given task, and here's how to use it.
1.1 Threadpoolexecutor tectonic method and its role
Threadpoolexecutor the method of construction in the source code:
- corePoolSize:线程池维护线程的最少数量- maximumPoolSize:线程池维护线程的最大数量- keepAliveTime: 线程池维护线程所允许的空闲时间- unit: 线程池维护线程所允许的空闲时间的单位- workQueue: 线程池所使用的缓冲队列- handler: 线程池对拒绝任务的处理策略
1.2 Thread Count Control
The number of threads in the threadpoolexecutor thread pool is variable and varies depending on the following two variables:
1. corePoolSize:线程池维护线程的最少数量2. maximumPoolSize:线程池维护线程的最大数量
The specific thread is assigned in a way that when a task is added to the thread pool:
1. 如果此时线程池中的数量小于corePoolSize,即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。2. 如果此时线程池中的数量等于 corePoolSize,但是缓冲队列 workQueue未满,那么任务被放入缓冲队列。3. 如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maximumPoolSize,建新的线程来处理被添加的任务。4. 如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maximumPoolSize,那么通过 handler所指定的策略来处理此任务。也就是:处理任务的优先级为:核心线程corePoolSize、任务队列workQueue、最大线程maximumPoolSize,如果三者都满了,使用handler处理被拒绝的任务。5. 当线程池中的线程数量大于 corePoolSize时,如果某线程空闲时间超过keepAliveTime,线程将被终止。
This allows the thread pool to dynamically adjust the number of threads in the pool. In corePoolSize
addition maximumPoolSize
to the two variables, the Threadpoolexecutor construction method has several parameters:
- keepAliveTime: 线程池维护线程所允许的空闲时间- unit: 线程池维护线程所允许的空闲时间的单位- workQueue: 线程池所使用的缓冲队列- handler: 线程池对拒绝任务的处理策略
1.2 Unit
The Unit optional parameter is a java.util.concurrent.TimeUnit
few static properties in:
- NANOSECONDS- MICROSECONDS- MILLISECONDS- SECONDS
1.3 WorkQueue
Workqueue is a blockingqueue, the default isLinkedBlockingQueue<Runnable>
1.4 Handler
Handler is the way the thread pool refuses to handle tasks, there are four main types:
- Threadpoolexecutor.abortpolicy () (system default): Throws Java.util.concurrent.RejectedExecutionException exception
- Threadpoolexecutor.callerrunspolicy (): The Rejectedexecution method is called when the Rejectedexecutionexception exception is thrown
- Threadpoolexecutor.discardoldestpolicy (): Abandon the old task
- Threadpoolexecutor.discardpolicy (): Discard the current task
1.5 Creating a Threadpoolexecutor
int corePoolSize = 5;int maxPoolSize = 10;long keepAliveTime = 5000;ExecutorService threadPoolExecutor = new ThreadPoolExecutor( corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>() );
Second, Scheduledthreadpoolexecutor
Scheduledthreadpoolexecutor is another implementation class of Executorservice, from the above Java thread pool Executorservice inheritance tree, as can be seen in the picture, Scheduledthreadpoolexecutor directly inherit from Scheduledexecutorservice, Scheduledthreadpoolexecutor The function of the class is also mainly embodied in the Scheduledexecutorservice interface, and so the Scheduledexecutorservice interface is introduced before introducing Scheduledthreadpoolexecutor.
2.1 Scheduledexecutorservice Interface Introduction
java.util.concurrent.ScheduledExecutorService
Interface inherits the Executorservice, and its main function is to dispatch the tasks, such as deferred execution, timed execution and so on.
Scheduledexecutorservice Interface Definition:
public interface ScheduledExecutorService extends ExecutorService { public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit); public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay, long period, TimeUnit unit); public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,long initialDelay, long delay,TimeUnit unit);}
From the above interface definition, we know that four methods are provided, and we will introduce each of the following:
1. schedule (Runnable task, long delay, TimeUnit timeunit)2. schedule (Callable task, long delay, TimeUnit timeunit)3. scheduleAtFixedRate (Runnable, long initialDelay, long period, TimeUnit timeunit)4. scheduleWithFixedDelay (Runnable, long initialDelay, long period, TimeUnit timeunit)
2.1.1 Schedule (Runnable task, long delay, timeunit timeunit)
This method means that the task is run after a specified delay. One problem with this approach is that there is no way to know the outcome of a task's execution. If we want to get the task execution result, we can pass in an instance of callable (described later).
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);ScheduledFuture scheduledFuture =scheduledExecutorService.schedule(new Callable() { public Object call() throws Exception { System.out.println("Executed!"); return "Called!"; }},5,TimeUnit.SECONDS);System.out.println("result = " + scheduledFuture.get());scheduledExecutorService.shutdown();
2.1.2 Schedule (callable task, long delay, timeunit timeunit)
This method schedule (Runnable task)
is similar to running a task after a specified delay, but it receives a callable instance, which returns a Schedulefuture object, and through Schedulefuture we can cancel an un-executed task. You can also get the execution result of this task.
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);ScheduledFuture scheduledFuture =scheduledExecutorService.schedule(new Callable() { public Object call() throws Exception { System.out.println("Executed!"); return "Called!"; }},5,TimeUnit.SECONDS);System.out.println("result = " + scheduledFuture.get());scheduledExecutorService.shutdown();
2.1.3 Scheduleatfixedrate (Runnable, long initialdelay, long period, timeunit Timeunit)
The function of this method is to schedule task execution periodically. The delay that the task executes for the first time is determined by the initialDelay
parameters, and each subsequent execution is interval period
.
If the task's execution time is greater than the defined period, then the next thread executes after the current thread finishes. The entire schedule guarantees that no more than one task will occur at the same time.
2.1.4 Schedulewithfixeddelay (Runnable, long initialdelay, long period, timeunit Timeunit)
The parameters of the Schedulewithfixeddelay are exactly the same as the scheduleatfixedrate parameters, and they differ in the interpretation of the period dispatch cycle.
In Scheduleatfixedrate, period refers to the interval between the time at which two tasks start executing, that is, the start time of the current task and the start execution time of the next task.
In Schedulewithfixeddelay, period refers to the end execution time of the current task to the start of the next task.
2.1.5 Scheduledexecutorservice's Off
Similar to Executorservice, we need to close the scheduledexecutorservice when we are done with it. If you do not close, the JVM will keep running straight, even if all the threads are closed.
Close Scheduledexecutorservice can use its inherited from the Executorservice interface shutdown()
and shutdownNow()
methods, the difference between the two refer to "Java Thread pool Executorservice".
2.2 Scheduledthreadpoolexecutor
Scheduledthreadpoolexecutor inherited from Threadpoolexecutor, the construction parameters are very simple, only 3:
1. int corePoolSize:线程池维护线程的最少数量2. ThreadFactory threadFactory:线程工程类,线程池用它来制造线程3. RejectedExecutionHandler handler:线程池对拒绝任务的处理策略
Please refer to Threadpoolexecutor or use executors for specific use.
Third, executors
Creating an instance of what Executorservice (that is, the thread pool) requires our specific application scenario, but Java provides us with a executors factory class that can help us easily create various types of executorservice thread pools, Executors altogether can create the following four types of thread pools:
1. newCachedThreadPool 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。2. newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。3. newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。4. newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
Note: Executors is just a factory class, and all of its methods return instances of the two classes, Threadpoolexecutor, Scheduledthreadpoolexecutor.
After reading this article, it is highly recommended to read the Java thread pool Executorservice.
Java thread pool class Threadpoolexecutor, Scheduledthreadpoolexecutor, and executors factory classes