线程VS线程池
普通线程使用
- 创建线程池
- 执行任务
- 执行完毕,释放线程对象
线程池
- 创建线程池
- 拿线程池线程去执行任务
- 执行完毕,放回线程池,等待执行其他任务
线程池优点
- 提高线程利用率
- 提高程序响应速度
- 统一管理线程对象
- 可以控制最大并发
线程池执行过程
1. 默认核心线程执行任务

2. 核心线程满了,进入等待区

3. 等待区满了,开启新线程

4. 线程满了,等待区满了,拒绝接收任务,抛出异常

5.长时间没有接收任务线程回收

Demo
fun testThreadPool() {
/**
* int corePoolSize, 核心线程
* int maximumPoolSize, 最大线程数
* long keepAliveTime, 存活时间
* TimeUnit unit, 时间单位
* BlockingQueue<Runnable> workQueue, 等待队列
* ThreadFactory threadFactory 线程工厂
* RejectedExecutionHandler handler 拒绝策略
*/
val executorService = ThreadPoolExecutor(
3,
5,
1,
TimeUnit.SECONDS,
ArrayBlockingQueue(3),
Executors.defaultThreadFactory(),
ThreadPoolExecutor.AbortPolicy()
) as ExecutorService
//执行任务
for (runnable in 0 until 1){
executorService.execute {
println("${Thread.currentThread().name} ====>执行任务")
}
}
//关闭线程池
executorService.shutdown()
}
当任务小于3由核心线程处理
pool-1-thread-1 ====>执行任务
pool-1-thread-2 ====>执行任务
pool-1-thread-3 ====>执行任务
当任务大于3则进入等待区,等待核心线程执行
pool-1-thread-3 ====>执行任务
pool-1-thread-2 ====>执行任务
pool-1-thread-3 ====>执行任务
pool-1-thread-1 ====>执行任务
pool-1-thread-3 ====>执行任务
pool-1-thread-2 ====>执行任务
任务数量大于等待区最大值,开启新的工作线程
pool-1-thread-3 ====>执行任务
pool-1-thread-3 ====>执行任务
pool-1-thread-3 ====>执行任务
pool-1-thread-3 ====>执行任务
pool-1-thread-1 ====>执行任务
pool-1-thread-4 ====>执行任务
pool-1-thread-2 ====>执行任务
线程和等待区都满了,拒绝接收,抛出异常
java.util.concurrent.RejectedExecutionException: Task
com.example.other.ExampleUnitTest$testThreadPool$1@3d012ddd rejected from
java.util.concurrent.ThreadPoolExecutor@6f2b958e[Running, pool size = 5, active threads = 5, queued tasks = 3, completed tasks = 0]
...
网友评论