首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java并发之ThreadPoolExecutor 线程执行服务

Java并发之ThreadPoolExecutor 线程执行服务

作者头像
WindWant
发布2020-09-11 10:48:30
2480
发布2020-09-11 10:48:30
举报
文章被收录于专栏:后端码事后端码事
 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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-10-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档