victory的博客

长安一片月,万户捣衣声

0%

并发 | 线程池

线程池

线程池的实现原理

线程池的使用
(1)线程池的创建

new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,unit,workQueue, handler)

Parameters:
    corePoolSize: the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
    maximumPoolSize: the maximum number of threads to allow in the pool
    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.
    unit the time: unit for the keepAliveTime argument
    workQueue:the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
    threadFactory: set thread factory
    handler: the handler to use when execution is blocked because the thread bounds and queue capacities are reached
    
workQueue:
    ArrayBlockingQueue:基于数组结构的有界阻塞队列
    LinkedBlockingQueue:基于链表结果的阻塞队列
    SynchronousQueue:不存储元素的阻塞队列
    PriorityBlockingQueue:具有优先级的无限阻塞队列

handler:
    AbortPolicy:直接抛出RejectedExecutionException异常
    CallerRunsPolicy:使用调用者所在线程来执行任务
    DiscardOldestPolicy:丢弃掉在队列中存在时间最久的任务
    DiscardPolicy:默认丢弃任务,不进行任何通知

创建线程池的7种方式
Executor框架

(2)向线程池提交任务
execute():用于提交不需要返回值的任务。
submit():用于提交需要返回值的任务。
(3)关闭线程池
shutdown()
shutdownNow()
线程池的配置
(1)
CPU密集型任务:配置 CPU数量+1 个线程的线程池;
IO密集型任务:配置 2*CPU数量 个线程的线程池;
混合型任务:两个事务执行时间相差不大,如果可以拆分,将其分解成一个CPU密集型任务和一个IO密集型任务,如果两个任务的执行时间相差太大,则没有必要拆分。
(2)优先级不同的任务可以使用优先级队列PriorityBlockingQueue来处理,让优先级高的任务先执行。
(3)执行时间不同的任务可以交给不同规模的线程池来处理,或者可以使用优先级队列,让执行时间段的任务先执行。
(4)依赖数据库连接池的任务,因为线程提交SQL后选哟等待数据库返回结果,等待的时间越长,则CPU空闲时间越长,应该设置较大的线程数。
(5)建议使用有界队列。