线程池自定义

* 线程池基础
* @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
posted @ 2019-05-13 17:01  fuguang  阅读(159)  评论(0编辑  收藏  举报