复习并发编程的基础知识之线程池及线程池的核心线程数设置

  • 并发编程中,线程池是很重要的一块内容。
    线程池是一种池化技术,线程池、字符串常量池和数据库链接池都属于池化技术。
    使用线程池的好处:
    1.提高了线程的利用率(想一想,我们不可能每打一个电话,就去买一部手机吧?),节省新启一个线程和销毁一个线程需要的资源消耗。
    2.提高了程序的响应速度
    3.方便统一管理线程对象
    4.可以控制最大的并发数

线程池的模型如下: 在这里插入图片描述
其实和在银行办理业务是一样的
银行排队办业务模型
对应关系如下:
顾客–》任务
线程池–》银行
线程池中的线程对象–》银行的服务窗口
队列–》座位

在java中我们在使用线程池的时候,

ExecutorService threadPoolExecutor = new ThreadPoolExecutor(3,
                  5, 
                  1L, 
                  TimeUnit.SECONDS, 
                  new ArrayBlockingQueue<>(3)
                , Executors.defaultThreadFactory(), 
                new ThreadPoolExecutor.AbortPolicy());

对应API

 /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} or {@code handler} is null
     */
 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值