美文网首页
java线程池

java线程池

作者: Method | 来源:发表于2021-05-31 23:14 被阅读0次

线程VS线程池

普通线程使用

  1. 创建线程池
  2. 执行任务
  3. 执行完毕,释放线程对象

线程池

  1. 创建线程池
  2. 拿线程池线程去执行任务
  3. 执行完毕,放回线程池,等待执行其他任务

线程池优点

  • 提高线程利用率
  • 提高程序响应速度
  • 统一管理线程对象
  • 可以控制最大并发

线程池执行过程

1. 默认核心线程执行任务

1.png

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

2.png

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

3.png

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

4.png

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

5.png

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]
...

相关文章

网友评论

      本文标题:java线程池

      本文链接:https://www.haomeiwen.com/subject/pnxnsltx.html