单例线程池

系统管理员 2022-10-11 12:27 249阅读 0赞
  1. package com.yhcookie;
  2. import java.util.concurrent.*;
  3. import java.util.concurrent.atomic.AtomicInteger;
  4. /** * 线程池 * @author yhcookie * @date 2021/4/23 18:37 */
  5. public class SingleThreadPoolExecutor extends ThreadPoolExecutor {
  6. private volatile static SingleThreadPoolExecutor threadPoolExecutor = null;
  7. private SingleThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
  8. super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
  9. }
  10. public static SingleThreadPoolExecutor getInstance(){
  11. if (null == threadPoolExecutor){
  12. synchronized (SingleThreadPoolExecutor.class){
  13. if (null == threadPoolExecutor){
  14. threadPoolExecutor = new SingleThreadPoolExecutor(
  15. 4,
  16. 100,
  17. 60,
  18. TimeUnit.SECONDS,
  19. new ArrayBlockingQueue<>(50),
  20. new LocalThreadFactory());
  21. }
  22. }
  23. }
  24. return threadPoolExecutor;
  25. }
  26. static class LocalThreadFactory implements ThreadFactory{
  27. private static final AtomicInteger poolNumber = new AtomicInteger(1);
  28. private final ThreadGroup group;
  29. private final AtomicInteger threadNumber = new AtomicInteger(1);
  30. private final String namePrefix;
  31. LocalThreadFactory() {
  32. SecurityManager s = System.getSecurityManager();
  33. this.group = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
  34. this.namePrefix = "xxxxxx-pool-" + poolNumber.getAndIncrement() + "-thread-";
  35. }
  36. @Override
  37. public Thread newThread(Runnable r) {
  38. Thread t = new Thread(this.group, r, this.namePrefix + this.threadNumber.getAndIncrement(), 0L);
  39. if (t.isDaemon()) {
  40. t.setDaemon(false);
  41. }
  42. if (t.getPriority() != 5) {
  43. t.setPriority(5);
  44. }
  45. return t;
  46. }
  47. }
  48. }

发表评论

表情:
评论列表 (有 0 条评论,249人围观)

还没有评论,来说两句吧...

相关阅读

    相关 线阻塞,模式

      以前自己理解不到位,单例模式下,只存在一个实例对象,那么在高并发的情况下,超级多的请求同时来访问这个类的同一个方法,那这个类忙的过来吗,还有这么多请求同时访问一个对象的方法