前言
java.util.concurrent.ExecutorService
接口表示一个异步执行机制,使我们能够在后台执行任务
ExecutorService
很类似于一个线程池
创建一个线程池
<correPoolSize>
:核心线程数。当线程池初次创建时,是没有任何线程的,当有请求发起时,会创建核心线程。在请求过程中,无论核心线程是否闲置,线程池都会创建核心线程,直到满足数量为止
<maximumPoolSize>
:最大线程数。当核心线程都满了,且队列也满了,会继续创建临时线程,核心线程和最大线程的总和不能超过最大线程数
<keepAliveTime>
:临时线程超时时间。当临时线程超过超时时间没有被使用,临时线程将会被销毁
<unit>
:超时时间的单位,TimeUnit.MILLISECONDS
为毫秒
<workQueue>
:等待队列
1 2 3 4 5 6 7
| ExecutorService executorService = new ThreadPoolExecutor( <correPoolSize>, <maximumPoolSize>, <keepAliveTime>, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10) );
|
提供拒绝服务
- 当核心线程数、等待队列、临时队列数都满时,再来的请求都会由拒绝服务处理
1 2 3 4 5 6 7 8 9 10 11 12 13
| ExecutorService executorService = new ThreadPoolExecutor( <correPoolSize>, <maximumPoolSize>, <keepAliveTime>, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { ... } } );
|
利用工具类创建线程池
大池子小队列
- 核心线程为0
- 最大线程为
Integer.MAX_VALUE
- 超时时间为
60L
- 单位为秒
- 队列为同步队列
1
| ExecutorService executorService = Executors.newCachedThreadPool();
|
小池子大队列
- 核心线程为
<num>
- 最大线程为
<num>
- 超时时间为
0L
- 单位为毫秒
- 队列为无界队列
1
| ExecutorService executorService = Executors.newFixedThreadPool(<num>);
|
创建一个线程
1 2 3 4 5 6
| class ClientRunner implements Runnable { @Override public void run() { ... } }
|
利用线程池创建线程
1
| executorService.execute(new ClientRunner());
|
关闭线程池
- 立即不对外提供服务了,但不会立即销毁线程池已经创建的线程
1
| executorService.shutdown();
|
完成