MultiThreadPoolServer.java
3.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.xly.thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.poi.ss.formula.functions.T;
import org.python.google.common.util.concurrent.ThreadFactoryBuilder;
/**
*
* 线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,
* 这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
* 说明:Executors各个方法的弊端:
* 1)newFixedThreadPool和newSingleThreadExecutor:
* 主要问题是堆积的请求处理队列可能会耗费非常大的内存,甚至OOM。
* 2)newCachedThreadPool和newScheduledThreadPool:
* 主要问题是线程数最大数是Integer.MAX_VALUE,可能会创建数量非常多的线程,甚至OOM。
* 功能:任务线程池类(2秒更新一次线程单独用)
* 工具类参考https://blog.csdn.net/bunnycoffer/article/details/82908024
* 作者:qb
* 日期:2018-11-13
* @author qianbao
*/
public class MultiThreadPoolServer {
/** ˽������线程池服务*/
private ExecutorService executorService;
private static MultiThreadPoolServer mts;
private final static int poolSize = 30000;
private final static int queueSize = 30000;
private static ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("theadpool" + "-%d").setDaemon(true).build();
/** 单例方法 */
public static MultiThreadPoolServer getInstance() {
//生成实例
if (mts == null) {
//锁类ͬ����
synchronized(MultiThreadPoolServer.class) {
if (mts == null) {
//实例化
mts = new MultiThreadPoolServer();
mts.executorService = new ThreadPoolExecutor(poolSize,
poolSize,
0L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(queueSize),
threadFactory,
new ThreadPoolExecutor.AbortPolicy() {
// 队列已满,而且当前线程数已经超过最大线程数时的异常处理策略
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
super.rejectedExecution(r, e);
}
});
}
}
}
//返回值
return mts;
}
/** 线程池调用方法 */
public void service(Runnable handler) {
try {
//调用线程
this.executorService.execute(handler);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 开启一个有返回结果的线程
* @param
* @return
*/
public Future<T> submit(Callable<T> handler) {
// 把一个任务丢到了线程池中
try {
//调用线程
return this.executorService.submit(handler);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/** 线程池结束 */
public void shutdown() {
this.executorService.shutdown();
}
}