zoukankan      html  css  js  c++  java
  • 线程池自定义

    * 线程池基础
    * @author kf
    * 自定义线程池 并测试4种拒绝策略
    * 拒绝策略AbortPolicy 当任务数大于总线程数时 报错:java.util.concurrent.RejectedExecutionException
    * 拒绝策略CallerRunsPolicy 当任务数大于总线程数时 不能接受处理的任务退给调用者,即main线程
    * 拒绝策略DiscardOldestPolicy 当任务数大于总线程数时 扔掉队列等待最久的任务,然后加入新的任务到队列再次尝试执行
    * 拒绝策略DiscardPolicy 当任务数大于总线程数时 直接扔掉
    *
    * 配置线程池的线程数的方法:
    * 考虑程序是 CPU密集 IO密集
    * 如果是CPU密集 一般公式:CPU核心数+1个线程的线程池
    * 如果是IO密集 即任务需要大量的IO,即大量的阻塞。
    * 公式:CPU核心数/1-阻塞系数 阻塞系数在0.8--0.9之间 比如8核CPU: 8/(1-0.9) = 80

    public class ExecutorServiceDemo {
        public static void main(String[] args) {
            
            //ExecutorService t1 = Executors.newCachedThreadPool();
            //ExecutorService t2 = Executors.newFixedThreadPool(5);
            //ExecutorService t3 = Executors.newSingleThreadExecutor();
            //ExecutorService t4 = Executors.newScheduledThreadPool(2);
            
            ExecutorService t = new ThreadPoolExecutor(2, 5, 1, TimeUnit.SECONDS, new LinkedBlockingDeque<>(3), 
                    Executors.defaultThreadFactory() , new ThreadPoolExecutor.DiscardPolicy());
            
            try {
                for(int i=1;i<=10;i++){
                    t.execute(new Thread(()->{
                        System.out.println(Thread.currentThread().getName()+"办理业务");
                    },""+i));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //执行完毕 关闭
                t.shutdown();
            }
            
            
        }
    
    }
    View Code
  • 相关阅读:
    决策树(chap3)Machine Learning In Action学习笔记
    AdaBoost-Machine Learning In Action学习笔记
    支持向量机-Machine Learning In Action学习笔记
    Alamofire 4.0 迁移指南
    从VSS到SVN再到Git 记Git的基本操作
    倍杀测量者
    P3166 数三角形
    APIO2014 序列分割(斜率优化好题)
    P3694 邦邦的大合唱站队
    ACwing 298 栅栏(单调队列DP)
  • 原文地址:https://www.cnblogs.com/fuguang/p/10857650.html
Copyright © 2011-2022 走看看