xiangpei
2025-06-12 8bfcdc67288b607e333da334ec84abc58ff6dfc4
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
package cn.lili.common.utils;
 
import java.util.concurrent.*;
 
/**
 * @author Chopper
 */
public class ThreadPoolUtil {
 
    /**
     * 核心线程数,会一直存活,即使没有任务,线程池也会维护线程的最少数量
     */
    private static final int SIZE_CORE_POOL = 5;
    /**
     * 线程池维护线程的最大数量
     */
    private static final int SIZE_MAX_POOL = 10;
    /**
     * 线程池维护线程所允许的空闲时间
     */
    private static final long ALIVE_TIME = 2000;
    /**
     * 线程缓冲队列
     */
    private static final BlockingQueue<Runnable> BQUEUE = new ArrayBlockingQueue<Runnable>(100);
    private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, ALIVE_TIME, TimeUnit.MILLISECONDS, BQUEUE,
            new ThreadPoolExecutor.CallerRunsPolicy());
    /**
     * volatile禁止指令重排
     */
    public static volatile ThreadPoolExecutor threadPool;
 
    static {
        POOL.prestartAllCoreThreads();
    }
 
    /**
     * 执行方法
     *
     * @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);
    }
 
    /**
     * DCL获取线程池
     *
     * @return 线程池对象
     */
    public static ThreadPoolExecutor getThreadPool() {
        if (threadPool != null) {
            return threadPool;
        }
        synchronized (ThreadPoolUtil.class) {
            if (threadPool == null) {
                threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            }
        }
        return threadPool;
    }
 
    public static ThreadPoolExecutor getPool() {
        return POOL;
    }
 
    public static void main(String[] args) {
        System.out.println(POOL.getPoolSize());
    }
}