Java并发之ThreadPoolExecutor 线程执行服务

时间:2021-08-01 18:36:32
 1 package com.thread.test.thread;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.LinkedBlockingQueue;
 5 import java.util.concurrent.RejectedExecutionHandler;
 6 import java.util.concurrent.ThreadLocalRandom;
 7 import java.util.concurrent.ThreadPoolExecutor;
 8 import java.util.concurrent.TimeUnit;
 9 
10 /**
11  * ThreadPoolExecutor
12  * 通过线程池执行所提交的任务的ExecutorService,通常由Executors生成
13  * 执行高并发任务比较高效,因为减少了任务的穿行等待时间,同时很好的管理着执行需求的资源,包括线程,
14  * 通常,维护者一些基础的任务执行数据,例如已完成任务数量
15  *
16  * ThreadPoolExecutor有许多可调正的参数,可以适用于不同的用途,但是通常我们使用
17  * Executors#newCachedThreadPool 无容量限制,线程自动回收
18  * Executors#newFixedThreadPool 固定容量线程池
19  * Executors#newSingleThreadExecutor 单线程
20  * 等为许多通用场景预置了很多参数,
21  *
22  * Hello world!
23  *
24  */
25 public class ThreadPoolFactoryTest
26 {
27     public static void main( String[] args )
28     {
29         /**
30          * @ int corePoolSize:线程池中维护的线程数量,生命周期同线程池,除非设置了allowCoreThreadTimeOut
31          * @ int maximumPoolSize:允许的最大数量
32          * @ long keepAliveTime:允许的最大存活时间
33          * @ TimeUnit unit:单位
34          * @ BlockingQueue<Runnable> workQueue:存储等待执行任务,execute提交的Runnable类型任务
35          * @ RejectedExecutionHandler handler:线程阻塞,队列已满时执行的操作
36          */
37         ExecutorService enew = new ThreadPoolExecutor(5, 20, 0L,
38                 TimeUnit.SECONDS,
39                 new LinkedBlockingQueue<Runnable>(),
40         new RejectedExecutionHandler() {
41                     public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
42                         System.out.println("this is the exception execution begin");
43                         executor.execute(r);
44                         System.out.println("this is the exception execution end");
45                     }
46                 });
47 
48         for (int i = 0; i < 100; i++) {
49             enew.execute(new Runnable() {
50                 public void run() {
51                     int l = ThreadLocalRandom.current().nextInt();
52                     System.out.println("task..." + l + "begin");
53                     try {
54                         Thread.sleep(2000);
55                         System.out.println("task..." + l + "end");
56                     } catch (InterruptedException e) {
57                         e.printStackTrace();
58                     }
59                 }
60             });
61         }
62         System.out.println("add end...");
63     }
64 }

项目地址:https://github.com/windwant/windwant-demo/tree/master/thread-demo