hjg
2024-02-05 301115d5e96b56cd093eee3fcff2d60a15184162
提交 | 用户 | 时间
c5bdf3 1 package com.mandi.fendan.util;
A 2
3 import javax.validation.constraints.NotNull;
301115 4 import java.util.concurrent.ScheduledThreadPoolExecutor;
c5bdf3 5 import java.util.concurrent.ThreadFactory;
A 6 import java.util.concurrent.ThreadPoolExecutor;
7 import java.util.concurrent.TimeUnit;
8 import java.util.concurrent.atomic.AtomicInteger;
9
10 /**
11  * 线程池的工具类
12  * 用于进行线程的管理,防止重复创建、杀死线程。
13  *
14
15  * 多线程运行期间,如果系统不断的创建、杀死新线程,
16  * 会产生过度消耗系统资源,以及过度切换线程的问题,甚至可能导致系统资源的崩溃。
17  * 因此需要线程池,对线程进行管理。
18  */
19 public class ThreadPoolUtil {
20
21     private String TAG = getClass().getName();
22     private static volatile ThreadPoolUtil mInstance;
23     //核心线程池的数量,同时能够执行的线程数量
24     private int corePoolSize;
25     //最大线程池数量,表示当缓冲队列满的时候能继续容纳的等待任务的数量
26     private int maxPoolSize;
27     //存活时间
28     private long keepAliveTime = 1;
29     private TimeUnit unit = TimeUnit.HOURS;
301115 30 //    private ThreadPoolExecutor executor;
c5bdf3 31
301115 32     ScheduledThreadPoolExecutor executor;
c5bdf3 33     private ThreadPoolUtil() {
A 34         //给corePoolSize赋值:当前设备可用处理器核心数*2 + 1,能够让cpu的效率得到最大程度执行(有研究论证的)
35         corePoolSize = Runtime.getRuntime().availableProcessors() * 2 + 1;
36         maxPoolSize = corePoolSize;
301115 37 //        executor = new ThreadPoolExecutor(
H 38 //                //当某个核心任务执行完毕,会依次从缓冲队列中取出等待任务
39 //                corePoolSize,
40 //                // 然后new LinkedBlockingQueue(),然后maximumPoolSize,但是它的数量是包含了corePoolSize的
41 //                maxPoolSize,
42 //                //表示的是maximumPoolSize当中等待任务的存活时间
43 //                keepAliveTime,
44 //                unit,
45 //                //缓冲队列,用于存放等待任务,Linked的先进先出
46 //                new LinkedBlockingQueue(),
47 //                new DefaultThreadFactory(Thread.NORM_PRIORITY, "thread-pool-"),
48 //                new ThreadPoolExecutor.AbortPolicy()
49 //        );
50           executor =  new ScheduledThreadPoolExecutor(corePoolSize);
c5bdf3 51     }
A 52
53     public static ThreadPoolUtil getInstance() {
54         if (mInstance == null) {
55             synchronized (ThreadPoolUtil.class) {
56                 if (mInstance == null) {
57                     mInstance = new ThreadPoolUtil();
58                 }
59             }
60         }
61         return mInstance;
62     }
63
64     /**
65      * 执行任务
66      *
67      * @param runnable
68      */
69     public void execute(Runnable runnable) {
301115 70         checkNull();
H 71         if (runnable != null) {
72             executor.execute(runnable);
73         }
74     }
75
76     void checkNull() {
c5bdf3 77         if (executor == null) {
301115 78 //            executor = new ThreadPoolExecutor(
H 79 //                    corePoolSize,
80 //                    maxPoolSize,
81 //                    keepAliveTime,
82 //                    TimeUnit.SECONDS,
83 //                    new LinkedBlockingQueue(),
84 //                    new DefaultThreadFactory(Thread.NORM_PRIORITY, "thread-pool-"),
85 //                    new ThreadPoolExecutor.AbortPolicy());
86             executor =  new ScheduledThreadPoolExecutor(corePoolSize,
c5bdf3 87                     new DefaultThreadFactory(Thread.NORM_PRIORITY, "thread-pool-"),
A 88                     new ThreadPoolExecutor.AbortPolicy());
89         }
301115 90     }
H 91     /**
92      *
93      * @param runnable
94      * @param delay 延迟执行,单位毫秒
95      */
96     public void execute(Runnable runnable,long delay) {
97         checkNull();
c5bdf3 98         if (runnable != null) {
301115 99             executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
c5bdf3 100         }
A 101     }
102
103     /**
104      * 移除任务
105      *
106      * @param runnable
107      */
108     public void remove(Runnable runnable) {
109         if (runnable != null) {
110             executor.remove(runnable);
111         }
112     }
113
114     private static class DefaultThreadFactory implements ThreadFactory {
115         //线程池的计数
116         private static final AtomicInteger poolNumber = new AtomicInteger(1);
117         //线程的计数
118         private final AtomicInteger threadNumber = new AtomicInteger(1);
119         private final ThreadGroup group;
120         private final String namePrefix;
121         private final int threadPriority;
122
123         DefaultThreadFactory(int threadPriority, String threadNamePrefix) {
124             this.threadPriority = threadPriority;
125             this.group = Thread.currentThread().getThreadGroup();
126             this.namePrefix = threadNamePrefix + poolNumber.getAndIncrement() + "-thread-";
127         }
128
129         @Override
130         public Thread newThread(@NotNull Runnable r) {
131             Thread thread = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
132             // 返回True该线程就是守护线程
133             // 守护线程应该永远不去访问固有资源,如:数据库、文件等。因为它会在任何时候甚至在一个操作的中间发生中断。
134             if (thread.isDaemon()) {
135                 thread.setDaemon(false);
136             }
137             thread.setPriority(threadPriority);
138             return thread;
139         }
140     }
141 }