线程池

一.两种线程池

线程池成员有ThreadPoolExecutor与ScheduledThreadPoolExecutor

1.ThreadPoolExecutor

ThreadPoolExecutor有3种 调用的最终实例化方法都是一个,但参数差异较大

1.1 FixedThreadPool

适用于为了满足资源管理的需求 而需要限制当前线程数量的应用场景 适用于负载较重的服务器

      //不传ThreadFactory() 默认是Executors.defaultThreadFactory()
      ExecutorService fixedService = Executors.newFixedThreadPool(10);
      ThreadPoolExecutor fixedExecutor = new ThreadPoolExecutor(10, 10,
              0L, TimeUnit.MILLISECONDS,
              new LinkedBlockingQueue<Runnable>());
      //传完整参数 线程工厂 和reject异常处理
      ThreadPoolExecutor fullParams = new ThreadPoolExecutor(10, 10,
              0L, TimeUnit.MILLISECONDS,
              new LinkedBlockingQueue<Runnable>(), Executors.privilegedThreadFactory(),
              new RejectedExecutionHandler() {
                  public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                      System.out.println("rejectedExecution发生");
                  }
              });

1.2 SingleThreadExecutor

创建使用单个线程,使用于需要保证顺序执行 各个任务 并且在任意时间点 不会有多线程活动 适用于单线程场景,如某个服务异步启动
SingleThreadExecutor的初始化通过FinalizableDelegatedExecutorService包装
FinalizableDelegatedExecutorService对象就是对代理对象DelegatedExecutorService又包了一层确保垃圾回收销毁线程。

 ExecutorService singleExecutor = Executors.newSingleThreadExecutor();
//方法实现
//这里是LinkedBlockingQueue
   public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

1.3 CachedThreadPool

大小无界的线程池 适用于执行很多 短期异步任务的小程序 或者是负载较轻的服务器
CachedThreadPool 使用没有容量的SynchronousQueue 当主线程提交任务的速度 高于线程池处理任务的速度时候 由于CachedThreadPool会不断创建新的线程 有可能会耗尽内存资源

ExecutorService cachedExecutor = Executors.newCachedThreadPool();
//方法实现
//这里用 SynchronousQueue实现
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

2.ScheduledThreadPoolExecutor

定时执行任务

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。