手动创建线程池,效果会更好哦

今天在回顾线程池的创建时,使用Executors创建线程池报错了,出现了以下问题:手动创建线程池,效果会更好哦。
在这里插入图片描述

查阅了阿里巴巴Java开发手册

在这里插入图片描述

回顾一下,通过ThreadPoolExecutor来创建。

找一下源码

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.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

源码中我们看到了ThreadPoolExecutor的七大参数。

corePoolSize:核心线程池大小
maximumPoolSize:最大核心线程池大小
keepAliveTime:空闲线程存活时间
unit:时间单位
workQueue:阻塞队列
threadFactory:线程工厂:创建线程的,一般不用动
handler:拒绝策略

当然,还有我们要了解的四种拒绝策略。
在这里插入图片描述

new ThreadPoolExecutor.AbortPolicy() // 不执行新任务,直接抛出异常,提示线程池已满
new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里!由调用线程处理该任务
new ThreadPoolExecutor.DiscardPolicy() //不执行新任务,也不抛出异常
new ThreadPoolExecutor.DiscardOldestPolicy() //丢弃队列最前面的任务,然后重新提交被拒绝的任务。
 ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());
  • 12
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
确实,手动创建线程池可以更好地控制线程的数量和执行方式。以下是一个使用手动创建线程池的 CountDownLatch 示例: ```java import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchExample { public static void main(String[] args) throws InterruptedException { int taskCount = 3; CountDownLatch latch = new CountDownLatch(taskCount); ExecutorService executor = createThreadPool(taskCount); for (int i = 0; i < taskCount; i++) { executor.submit(new Task(latch)); } latch.await(); System.out.println("All tasks have finished, now executing main task."); executor.shutdown(); } static ExecutorService createThreadPool(int threadCount) { return Executors.newFixedThreadPool(threadCount); } static class Task implements Runnable { private CountDownLatch latch; public Task(CountDownLatch latch) { this.latch = latch; } @Override public void run() { try { System.out.println("Task started: " + Thread.currentThread().getName()); Thread.sleep(1000); System.out.println("Task finished: " + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } finally { latch.countDown(); } } } } ``` 在这个例子中,我们通过 `createThreadPool()` 方法手动创建了一个固定大小的线程池,并将线程池作为参数传递给 `ExecutorService`。这样我们就可以更好地控制线程池的行为,例如指定线程池的大小等。其余部分的逻辑和之前的例子相同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值