package com.lyon.juc.pool; import java.util.concurrent.*; public class Demo01 { public static void main(String[] args) { //不建议使用Executors去创建线程池,因为最大线程数是默认的Integer.MAX_VALUE 2的31次方-1(可能导致内存溢出) //使用原生线程池 ThreadPoolExecutor //最大线程如何定义: //1.cpu密集型 几个核心(逻辑处理器) 定义几个 //System.out.println(Runtime.getRuntime().availableProcessors()); //2.IO密集型 判断程序中十分耗IO的线程,设置最大数超过他 ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5,//当前线程最大并发数 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(3),//候客区 Executors.defaultThreadFactory(), //new ThreadPoolExecutor.AbortPolicy() //满了,再进来的线程,不处理,直接抛异常 //new ThreadPoolExecutor.CallerRunsPolicy()//满了,返回回去,这里会让main线程处理 //new ThreadPoolExecutor.DiscardPolicy()//满了,再进来的线程,不处理,不会抛异常 new ThreadPoolExecutor.DiscardOldestPolicy()//满了,再进来的线程,尝试去获取cpu时间片,会与最早的线程竞争,不会抛异常 ); try { //超出5+3 会抛异常 RejectedExecutionException for (int i = 0; i < 9; i++) { threadPoolExecutor.execute(()->{ System.out.println(Thread.currentThread().getName()); }); } }catch (Exception e) { e.printStackTrace(); }finally { //线程池,使用完,要关闭 threadPoolExecutor.shutdown(); } } }
多线程之ThreadPoolExecutor创建原生线程池
最新推荐文章于 2023-04-03 14:12:38 发布