ThreadPoolExecutor线程池的具体用法
创始人
2024-12-22 20:22:16
0次

ThreadPoolExecutor

ThreadPoolExecutor线程池,java提供开发框架,管理线程的创建、销毁、优化、监控等。

有4种不同的任务队列:

1.ArrayBlockingQueue:基于数组结构的任务队列。此队列按先进先出的原则对任务进行排序。

2.LinkedBlockingQueue:基于链表结构的任务队列。此队列也是按先进先出的原则对任务进行排序。但性能比ArrayBlockingQueue高。

3.synchronousQueue:不存储元素的任务队列。每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态。

4.PriorityBlockingQueue:具有优先级的任务队列。此队列中的元素必须能够比较。

拒绝策略:

RejectedExecutionHandler(饱和策略 ):当线程池中的线程数大于maximumPoolSize时,线程池就不能在处理任何任务了,这时线程池会抛出异常。原因就是这个策略默认情况下是AbortPolicy:表示无法处理新任务时抛出异常。

1.AbortPolicy:直接抛出异常。

2.CallerRunsPolicy:只用调用者所在线程来运行任务。

3.DiscardOldestPolicy:丢弃队列里最近的一个任务,并执行当前任务

4.DiscardPolicy:不处理,丢弃掉。自定义:ThreadPoolExecutor.AbortPolicy()//抛出java.util.concurrent.RejectedExecutionException异常ThreadPoolExecutor.CallerRunsPolicy()//重试添加当前的任务,他会自动重复调用execute()方法ThreadPoolExecutor.DiscardOldestPolicy()//抛弃旧的任务ThreadPoolExecutor.DiscardPolicy()// 抛弃当前的任务

private static class RecjectThreadHandler implements RejectedExecutionHandler  {    @Override    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {    }    // 异常记录    private void doLog(Runnable r, ThreadPoolExecutor executor)    {      System.out.println(r.toString()+"excutor failed."+executor.getCompletedTaskCount());    }  }

创建线程工厂:

用来创建线程。

public class CheckThreadFactory implements ThreadFactory{  private String threadGroupName;  private AtomicInteger count = new AtomicInteger(0);  public CheckThreadFactory(String threadGroupName) {    this.threadGroupName = threadGroupName;  }  @Override  public Thread newThread(Runnable r)  {    Thread thread = new Thread(r);    thread.setName(threadGroupName+"--"+count.addAndGet(1));    thread.setPriority(5);    thread.setDaemon(true);.// 设置为守护线程, 默认为主线程    return thread;  }}

线程工具类:

/** * @author Donald * @create 2019-09-21 21:40 */public class CheckExcetPool{  // 线程池核心线程数  private static int corePoolSize = Runtime.getRuntime().availableProcessors() * 5;  // 最大线程数  private static int maximumPoolSize = corePoolSize > 255 ? 255 : corePoolSize * 2;  // 线程池中除了核心线程,其他线程的最大存活时间  private static int keepAliveTime = 60;  // 时间单位  private static TimeUnit timeUnit = TimeUnit.SECONDS;  // 线程等待队列  private static BlockingQueue queue = new LinkedBlockingQueue();  //private static BlockingQueue queue = new ArrayBlockingQueue(30);  // 创建线程的工厂  private static CheckThreadFactory checkThreadFactory = new CheckThreadFactory("checkGroup");  // 拒绝策略 当提交任务数超过maxmumPoolSize+workQueue之和时,  //   *    即当提交第41个任务时(前面线程都没有执行完,此测试方法中用sleep(100)),  //   *         任务会交给RejectedExecutionHandler来处理  /*handler的拒绝策略:  有四种:第一种AbortPolicy:不执行新任务,直接抛出异常,提示线程池已满  第二种DisCardPolicy:不执行新任务,也不抛出异常  第三种DisCardOldSetPolicy:将消息队列中的第一个任务替换为当前新进来的任务执行  第四种CallerRunsPolicy:直接调用execute来执行当前任务*/  private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(      corePoolSize,      maximumPoolSize,      keepAliveTime,      timeUnit,      queue,      checkThreadFactory  );  public static void submit( Runnable runnable)  {    System.out.println(corePoolSize+"::"+queue.size());    threadPoolExecutor.submit(runnable);  }  public static Future submit(Callable callable)  {    return threadPoolExecutor.submit(callable);  }  public static void excutor( Runnable run, T result )  {    threadPoolExecutor.submit( run,result );  }  public static void excutor( Runnable run)  {    threadPoolExecutor.execute( run);  }  private static class RecjectThreadHandler implements RejectedExecutionHandler  {    @Override    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {    }    // 异常记录    private void doLog(Runnable r, ThreadPoolExecutor executor)    {      System.out.println(r.toString()+"excutor failed."+executor.getCompletedTaskCount());    }  }}

线程服务类,实现runnable 接口:

/** * @author Donald * @create 2019-09-21 23:00 */public class ThreadService implements Runnable{  private CountDownLatch countDownLatch;  private UserInterface userInterface;  public ThreadService(CountDownLatch countDownLatch, UserInterface userInterface) {    this.countDownLatch = countDownLatch;    this.userInterface = userInterface;  }  @Override  public void run()  {    try {      long start = System.currentTimeMillis();      userInterface.doSomething();      System.err.println(String.format("user time :%s",System.currentTimeMillis()-start));      Thread.sleep(1000);    }catch ( Exception e)    {      e.printStackTrace();    }finally {      countDownLatch.countDown();    }  }}

具体业务逻辑:

/** * @author Donald * @create 2019-09-21 22:51 */public interface UserInterface{  void doSomething();}

业务类:

/** * @author Donald * @create 2019-09-21 22:51 */public class UserService implements UserInterface{  private int number;  public UserService(int number) {    this.number = number;  }  @Override  public void doSomething() {    System.out.println(Thread.currentThread().getName()+"<<<<"+number);  }}

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...