Utils-线程池和线程数管理工具类

  根据 CPU 内核数计算出合理的线程并发数,线程池管理和关闭。

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
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* @ClassName ThreadManagerUtil
* @Description 线程池工具类
**/
public class ThreadManagerUtil {
public static ThreadPool instance;

// 获取单例的线程池对象
public static ThreadPool getInstance() {
if (instance == null) {
synchronized (ThreadManagerUtil.class) {
if (instance == null) {
int cpuNum = Runtime.getRuntime().availableProcessors();// 获取处理器数量
int threadNum = cpuNum * 2 + 1;// 根据cpu数量,计算出合理的线程并发数
instance = new ThreadPool(threadNum-1, threadNum, Integer.MAX_VALUE);
}
}
}
return instance;
}

public static class ThreadPool {
private ThreadPoolExecutor mExecutor;
private int corePoolSize;
private int maximumPoolSize;
private long keepAliveTime;

private ThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.keepAliveTime = keepAliveTime;
}

public void execute(Runnable runnable) {
if (runnable == null) {
return;
}
if (mExecutor == null) {
mExecutor = new ThreadPoolExecutor(corePoolSize,// 核心线程数
maximumPoolSize, // 最大线程数
keepAliveTime, // 闲置线程存活时间
TimeUnit.MILLISECONDS,// 时间单位
new LinkedBlockingDeque<Runnable>(Integer.MAX_VALUE),// 线程队列
Executors.defaultThreadFactory(),// 线程工厂
new ThreadPoolExecutor.AbortPolicy() {// 队列已满,而且当前线程数已经超过最大线程数时的异常处理策略
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
super.rejectedExecution(r, e);
}
}
);
}
mExecutor.execute(runnable);
}


// 从线程队列中移除对象
public void cancel(Runnable runnable) {
if (mExecutor != null) {
mExecutor.getQueue().remove(runnable);
}
}

// 待以前提交的任务执行完毕后关闭线程池
public void shutdown(){
mExecutor.shutdown();
}
}
}

Utils-线程池和线程数管理工具类

http://blog.gxitsky.com/2018/07/24/Utils-thread-pool-manager/

作者

光星

发布于

2018-07-24

更新于

2022-06-17

许可协议

评论