线程池

90 阅读1分钟

三大方法:

package pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {
  public static void main(String[] args) {
    ExecutorService threadPool = Executors.newSingleThreadExecutor();
    //ExecutorService threadPool = Executors.newFixedThreadPool(5);
    //ExecutorService threadPool = Executors.newCachedThreadPool();
    
    for (int i = 0; i < 100; i++) {
        threadPool.execute(
          new Thread(
              () -> {
                System.out.println(Thread.currentThread().getName()+"  ok");
              }));
    }
      threadPool.shutdown();
  }
}

他们的本质都是通过ThreadLocalPool来实现的,所以阿里开发手册建议使用这个来创建线程池,这样能使我们更加了解线程池底层的机制。

image.png

七大参数:

                int corePoolSize,//核心线程数
                int maximumPoolSize,//能够执行的最大线程数,包括核心线程数
                long keepAliveTime,//线程最大存活时间,如果没人调用就要被销毁了
                TimeUnit unit,//`keepAliveTime` 参数的时间单位
                BlockingQueue<Runnable> workQueue,//当达到最大核心线程数是,会直接存放到这里等待
                ThreadFactory threadFactory,//线程创建工厂
                RejectedExecutionHandler handler//线程拒绝策略

image.png 源码注释中也有对这七个参数进行解释

image.png