自定义线程池以及拒绝执行策略

 1 package com.duchong.demo.demox.hutool.threadpool;
 2 
 3 import com.google.common.util.concurrent.ThreadFactoryBuilder;
 4 
 5 import java.util.ArrayList;
 6 import java.util.List;
 7 import java.util.concurrent.LinkedBlockingQueue;
 8 import java.util.concurrent.ThreadFactory;
 9 import java.util.concurrent.ThreadPoolExecutor;
10 import java.util.concurrent.TimeUnit;
11 
12 /**
13  * 自定义线程池
14  * @author DUCHONG
15  * @since 2019-09-04 9:54
16  **/
17 public class DiyThreadPool {
18 
19     private static int maxNum=30;
20 
21     public static void main(String[] args)throws Exception {
22         //被拒绝执行的任务Runnable集合
23         List<Runnable> rejectTask=new ArrayList<>();
24         //设置预先创建线程的名称格式
25         ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("DiyThreadPool-%s").build();
26         ThreadPoolExecutor poolExecutor=new ThreadPoolExecutor(2,5,10, TimeUnit.SECONDS, new LinkedBlockingQueue <Runnable> (10) ,threadFactory,
27                 (r,executor)->{
28                 //把拒绝的任务记录日志,然后空闲时间解析再重新执行
29                 System.out.println("当前被拒绝任务为:" + r.toString());
30                 System.out.println("当前线程池大小为:"+executor.getPoolSize());
31 
32                 rejectTask.add(r);
33             }
34         );
35 
36         for (int i=1;i<=maxNum;i++){
37             poolExecutor.execute(new Task("task---"+i));
38         }
39 
40         poolExecutor.shutdown();
41 
42         System.out.println("需要继续执行的任务列表:");
43         rejectTask.forEach(System.out::println);
44     }
45 
46 
47     /**
48      * 内部task线程类
49      */
50     static class Task extends Thread{
51 
52         String taskName;
53         Task(String taskName){
54             super(taskName);
55             this.taskName=taskName;
56         }
57 
58         @Override
59         public void run() {
60 
61             System.out.println(Thread.currentThread().getName()+"----执行任务---"+taskName);
62         }
63     }
64 }

猜你喜欢

转载自www.cnblogs.com/geekdc/p/11462964.html
今日推荐