1. 线程池

Executor 接口,ExecutorService 接口 AbstractExecutorService ThreadPoolExecutor

  1. public ThreadPoolExecutor(int corePoolSize,
  2. int maximumPoolSize,
  3. long keepAliveTime,
  4. TimeUnit unit,
  5. BlockingQueue<Runnable> workQueue,
  6. ThreadFactory threadFactory) {
  7. ...
  8. }
  1. corePoolSize 核心线程数量
  2. maximumPoolSize 最大线程数量
  3. keepAliveTime 非核心线程空闲时等待下一个任务的时间
  4. unit 指的是 keepAliveTime 的单位
  5. workQueue 任务队列
  6. threadFactory 线程工厂,设置 thread 相关参数

·
执行流程

  1. execute 一个线程后,如果核心线程未满,则启用核心线程执行
  2. 如果核心线程满了且 workQueue 未满,则把新线程放入 workQueue 中等待
  3. 如果 核心线程满了且 workQueue 也满了,则开启非核心线程执行任务
  4. 如果线程数比非核心线程数还多,则拒绝执行,根据拒绝策略执行相应逻辑

常用线程池

  1. FixedThreadPool

只有核心线程 且 队列无上限

  1. public static ExecutorService newFixedThreadPool(int nThreads) {
  2. return new ThreadPoolExecutor(nThreads, nThreads,
  3. 0L, TimeUnit.MILLISECONDS,
  4. new LinkedBlockingQueue<Runnable>());
  5. }
  1. CachedThreadPool

无核心线程,非核心线程数量为Integer.MAX_VALUE,任务队列为 SynchronousQueue

  1. public static ExecutorService newCachedThreadPool() {
  2. return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
  3. 60L, TimeUnit.SECONDS,
  4. new SynchronousQueue<Runnable>());
  5. }
  1. SingleThreadPool

只有一个核心线程,队列无限

  1. public static ExecutorService newSingleThreadExecutor() {
  2. return new FinalizableDelegatedExecutorService
  3. (new ThreadPoolExecutor(1, 1,
  4. 0L, TimeUnit.MILLISECONDS,
  5. new LinkedBlockingQueue<Runnable>()));
  6. }
  1. ScheduledThreadPool

延时启动的线程池

  1. public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
  2. return new ScheduledThreadPoolExecutor(corePoolSize);
  3. }
  4. public ScheduledThreadPoolExecutor(int corePoolSize) {
  5. super(corePoolSize, Integer.MAX_VALUE,
  6. DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
  7. new DelayedWorkQueue());
  8. }

2. Java中的线程安全

3. 线程同步和通信

4. 进程间通信