執行緒池單例模式實現的兩種方式
阿新 • • 發佈:2020-10-14
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, longdelay) { 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 GuardFileCleanThreadPool { 2 private final ScheduledThreadPoolExecutor executorService; 3 4 private GuardFileCleanThreadPool() { 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 GuardFileCleanThreadPool 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 }