首页 > 编程知识 正文

线程池的创建方式,线程池几种方式

时间:2023-05-05 23:19:24 阅读:42491 作者:2004

文章目录Executors概述newcachedthreadpoolnewfixedthreadpoolnewscheduledthreadpoolnewsinglethreadexecutor线程池的四个拒绝策略

执行概述

Executors类位于java.util.concurrent包下。

Java通过执行程序提供了四种类型的线程池:

newCachedThreadPool创建一个可缓存的线程池。 如果线程池的长度超过需要处理的长度,请灵活地重用空闲线程,如果无法重用,请创建新线程。

newFixedThreadPool创建了一个固定长度的线程池,用于控制线程的最大并发行数,超出的线程将在队列中等待。

newScheduledThreadPool创建固定长度的线程池,以支持计划和定期任务执行。

newSingleThreadExecutor创建单线程池,只在唯一的工作线程上执行任务,以确保所有任务都按指定顺序(FIFO、LIFO、优先级)执行。

newcachedthreadpoolpublicstaticexecutorservicenewcachedthreadpool ({ returnnewthreadpoolexecutor,0,//核心线程数integer.MMP ) //活动时间/单位new SynchronousQueueRunnable(//块队列SynchronousQueue :不包含元素的块队列。 每个put操作都必须等待take操作,否则无法添加元素。 支持公平锁定和非公平锁定。 同步队列的一个使用场景位于线程池中。 Executors.newCachedThreadPool ()使用的是SynchronousQueue。 如果需要,此线程池将在(新任务到来时)创建新线程,如果有可用线程,则将其重用;如果有线程,则在60秒后回收。 newfixedthreadpoolpublicstaticexecutorservicenewfixedthreadpool (int nThreads (returnnewthreadpoolexecutor ) nthreads ) 此队列的长度为Integer.MAX_VALUE。 此队列按先进先出顺序排序。 LinkedBlockingQueue队列的长度被认为几乎无限大,因此在高并发场景中容易发生内存溢出。 ewscheduledthreadpool//executorspublicstaticscheduledexecutorservicenewscheduledthreadpool { intcorepoolsize } { return new scheduledthreadpoolexecutorpublicscheduledthreadpoolexecutor (intcorepoolsize (super ) corepoolsize,integer.max //使用案例scool scheduled thread pool.scheduleatfixedrate (new runnable ) { public void run } { system.out.println } delay1seconds,adadad delay queue :实现优先级块队列实现延迟捕获的无边界队列。 创建元素时,可以指定从队列中检索当前元素的时间。 只有经过延迟时间才能从队列中检索元素。 (可以在以下APP应用程序场景中利用DelayQueue : 1 .缓存系统设计:当DelayQueue存储缓存元素的有效期,并允许使用一个线程循环查询DelayQueue以从DelayQueue检索元素时,表示缓存有效期已到来。 2 .定时任务日程表。 使用DelayQueue保存当天执行的任务和执行时间,从DelayQueue获取任务后开始执行。 例如,从TimerQueue开始使用DelayQueue实现。 )

PriorityBlockingQueue (无边界队列,支持线程优先级)。 按默认自然顺序排序。 也可以定制和实现compareTo ) )方法,以指定元素的排序规则。 不能保证相同优先顺序的要素的顺序。

newsinglethreadexecutorpublicstaticexecutorservicenewsinglethreadexecutor () { returnnewfinalizabledelegatedexecutorservice () }线程池的四个拒绝策略thread pool executor.abort policy :放弃任务并抛出RejectedExecutionException异常。 线程池的默认拒绝策略。 thread pool executor.discard policy :放弃任务,但不抛出异常。 thread pool executor.discardoldestpolicy :放弃队列中的第一个任务,然后重新发送拒绝的任务。 thread pool executor.callerrunspolicy :调用线程(提交任务的线程)处理任务。 //Java.util.concurrent.thread pool executor类的源代码privatestaticfinalrejectedexecutionhandlerdefaulthandler=newabortor

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。