ThreadPoolUtil.java
1.9 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
package cn.fw.freya.utils;
import cn.hutool.core.thread.ThreadFactoryBuilder;
import java.util.concurrent.*;
/**
* @author wmy3969
* @version 1.0
* @date 2019/9/23 18:27
* @Description 线程池工具类
*/
public class ThreadPoolUtil {
/**
* 先定义ThreadPoolExecutor类型的静态成员变量
*/
public static ThreadPoolExecutor threadPool;
/**
* dcs获取线程池
*
* @return 线程池对象
*/
public static ThreadPoolExecutor getThreadPool() {
if (threadPool != null) {// 非首次调用该方法, threadPool不为null
return threadPool;// threadPool对象不为空, 直接返回
} else {
synchronized (ThreadPoolUtil.class) {// threadPool == null, 加锁
if (threadPool == null) {
threadPool = new ThreadPoolExecutor(
6,
12,
60,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(128),
new ThreadFactoryBuilder().setNamePrefix("capture-pool-").build(),
new ThreadPoolExecutor.DiscardPolicy());// 自行创建线程池, 并将创建好的线程池对象赋值给类的静态成员变量threadPool
}
return threadPool;// 将创建好的线程池对象返回
}
}
}
/**
* 无返回值直接执行
*
* @param runnable
*/
public static void execute(Runnable runnable) {
getThreadPool().execute(runnable);
}
/**
* 有返回值直接执行
*
* @param callable
*/
public static <T> Future<T> submit(Callable<T> callable) {
return getThreadPool().submit(callable);
}
/**
* 关闭线程池
*/
public static void shutdown() {
getThreadPool().shutdown();
}
}