线程池单例模式实现的两种方式

1. 使用enum枚举数据类型实现单例模式

复制代码
 1 public enum GroovyTimer {
 2     INSTANCE;
 3 
 4     private final AtomicInteger cacheTaskNumber = new AtomicInteger(1);
 5     private ScheduledExecutorService pruneTimer;
 6 
 7     GroovyTimer() {
 8         this.create();
 9     }
10 
11     public ScheduledFuture<?> schedule(Runnable task, long delay) {
12         return this.pruneTimer.scheduleAtFixedRate(task, delay, delay, TimeUnit.MILLISECONDS);
13     }
14 
15     public void create() {
16         if (null != this.pruneTimer) {
17             this.shutdownNow();
18         }
19 
20         this.pruneTimer = new ScheduledThreadPoolExecutor(1,
21                 (r) -> newGroovyThread(r, String.format("Groovy-Timer-%s", this.cacheTaskNumber.getAndIncrement())));
22     }
23     //
24     public Thread newGroovyThread(Runnable runnable, String name) {
25         Thread t = newThread(runnable, name, false);
26         if (t.getPriority() != 5) {
27             t.setPriority(5);
28         }
29 
30         return t;
31     }
32 
33     public static Thread newThread(Runnable runnable, String name, boolean isDaemon) {
34         Thread t = new Thread(null, runnable, name);
35         t.setDaemon(isDaemon);
36         return t;
37     }
38 
39 
40     public void shutdown() {
41         if (null != this.pruneTimer) {
42             this.pruneTimer.shutdown();
43         }
44 
45     }
46 
47     public List<Runnable> shutdownNow() {
48         return null != this.pruneTimer ? this.pruneTimer.shutdownNow() : null;
49     }
50 }
复制代码

2. 使用静态内置类实现单例模式

复制代码
 1 public class DukeFileCleanThreadPool {
 2     private final ScheduledThreadPoolExecutor executorService;
 3 
 4     private DukeFileCleanThreadPool() {
 5         executorService = new ScheduledThreadPoolExecutor(2,
 6                 new BasicThreadFactory.Builder().namingPattern("Guard-file-clean-pool-%d").build());
 7     }
 8 
 9     private static class SingletonHolder {
10         private static final GuardFileCleanThreadPool INSTANCE = new GuardFileCleanThreadPool();
11     }
12 
13     public static DukeFileCleanThreadPool getInstance() {return SingletonHolder.INSTANCE;}
14 
15     public void executeTask(Runnable command, long initialDelay, long period) {
16         executorService.scheduleAtFixedRate(command, initialDelay, period, TimeUnit.MILLISECONDS);
17         log.info("initiate file clean timer");
18     }
19 }
复制代码

 

posted @   屠城校尉杜  阅读(551)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示