线程池源码层级浅析

线程池最顶层是一个Executor接口,它只有一个Executor方法用来执行Runnable类型任务:

    public interface Executor {
        void execute(Runnable command);
    }

ExecutorService扩展了Executor,添加了控制线程池生命周期的方法,如关闭线程池shutDown()、shutDownNow(),判断线程池状态isShutdown()、isTerminated(),以及提交任务并异步返回Future类型结果的submit()方法等。

  public interface ExecutorService extends Executor {
      void shutdown();
  
      List<Runnable> shutdownNow();
  
      boolean isShutdown();
  
      boolean isTerminated();
  
      <T> Future<T> submit(Callable<T> task);
  
      <T> Future<T> submit(Runnable task, T result);
  
      Future<?> submit(Runnable task);
      ......
  }

AbstractExecutorService抽象类对ExecutorService重载的三个submit抽象方法进行了代码实现并新增了其他方法:

    public abstract class AbstractExecutorService implements ExecutorService {
        public Future<?> submit(Runnable task) {
            if (task == null) throw new NullPointerException();
            RunnableFuture<Void> ftask = newTaskFor(task, null);
            execute(ftask);
            return ftask;
        }
    
        public <T> Future<T> submit(Runnable task, T result) {
            if (task == null) throw new NullPointerException();
            RunnableFuture<T> ftask = newTaskFor(task, result);
            execute(ftask);
            return ftask;
        }
    
        public <T> Future<T> submit(Callable<T> task) {
            if (task == null) throw new NullPointerException();
            RunnableFuture<T> ftask = newTaskFor(task);
            execute(ftask);
            return ftask;
        }
        ......
    }

ThreadPoolExecutor拓展AbstractExecutorService并实现了ExecutorService接口,也是Executor框架默认的线程池实现类:

    public class ThreadPoolExecutor extends AbstractExecutorService {
        // runState is stored in the high-order bits
        private static final int RUNNING    = -1 << COUNT_BITS;
        private static final int SHUTDOWN   =  0 << COUNT_BITS;
        private static final int STOP       =  1 << COUNT_BITS;
        private static final int TIDYING    =  2 << COUNT_BITS;
        private static final int TERMINATED =  3 << COUNT_BITS;
        
        private final BlockingQueue<Runnable> workQueue;
        private volatile ThreadFactory threadFactory;
        private volatile RejectedExecutionHandler handler;
        private volatile long keepAliveTime;
        private volatile int corePoolSize;
        private volatile int maximumPoolSize;
        private static final RejectedExecutionHandler defaultHandler =
            new AbortPolicy();
        ......
    }

你可能感兴趣的:(Java并发)