JUC并发编程学习笔记 (6)

public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); } public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } 7大参数 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.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }

线程池运行逻辑参考银行办理业务或者工厂生产时的处理策略

4种拒绝策略 /** * new ThreadPoolExecutor.AbortPolicy() // 银行满了,还有人进来,不处理这个人的,抛出异常 * new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里! 调用方自己执行任务 * new ThreadPoolExecutor.DiscardPolicy() //队列满了,丢掉任务,不会抛出异常! * new ThreadPoolExecutor.DiscardOldestPolicy() //队列满了,尝试去和最早的竞争,丢弃任务,也不会 抛出异常! */ 线程池大小设置

CPU密集型——n+1 ,可以保持CPU的效率最高

IO密集型——2n

注意获取n的方法是通过代码获取Runtime.getRuntime().availableProcessors()

代码示例 public class ExecutorTest { public static void main(String[] args) { //CPU密集型 ThreadPoolExecutor executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() + 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy()); try { System.out.println(Runtime.getRuntime().availableProcessors()); for (int i = 0; i < 13; i++) { //使用线程池提交任务执行 executor.execute(() -> { System.out.println(Thread.currentThread().getName() + "执行完毕!"); }); } } catch (Exception e) { e.printStackTrace(); } finally { //关闭线程池 executor.shutdown(); } } /**输出: * 8 * pool-1-thread-1执行完毕! * pool-1-thread-3执行完毕! * pool-1-thread-2执行完毕! * pool-1-thread-4执行完毕! * pool-1-thread-5执行完毕! * pool-1-thread-6执行完毕! * pool-1-thread-8执行完毕! * pool-1-thread-6执行完毕! * main执行完毕! * pool-1-thread-6执行完毕! * pool-1-thread-7执行完毕! * pool-1-thread-9执行完毕! * pool-1-thread-8执行完毕! */ } ForkJoin

并行执行任务!提高效率。大数据量! 如果任务拆分地不好时反而不如单线程执行,所以要注意。

大数据:Map Reduce (把大任务拆分为小任务)

ForkJoin 特点:任务拆分和工作窃取

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyxsxy.html