java创建线程池一共有七种方式

java创建线程池一共有七种方式

这 7 种实现方法分别是:

Executors.newFixedThreadPool:创建一个固定大小的线程池,可控制并发的线程数,超出的线程会在队列中等待。
Executors.newCachedThreadPool:创建一个可缓存的线程池,若线程数超过处理所需,缓存一段时间后会回收,若线程数不够,则新建线程。
Executors.newSingleThreadExecutor:创建单个线程数的线程池,它可以保证先进先出的执行顺序。
Executors.newScheduledThreadPool:创建一个可以执行延迟任务的线程池。
Executors.newSingleThreadScheduledExecutor:创建一个单线程的可以执行延迟任务的线程池。
Executors.newWorkStealingPool:创建一个抢占式执行的线程池(任务执行顺序不确定)【JDK 1.8 添加】。
ThreadPoolExecutor:手动创建线程池的方式,它创建时最多可以设置 7 个参数。

一、用ExecutorService创建线程池

//1.创建一个大小为10的线程池
ExecutorService threadPool= Executors.newFixedThreadPool(10);
//给线程池添加任务
for (int i = 0;i < 10;i++){
    
    
    threadPool.submit(new Runnable() {
    
    
      @Override
      public synchronized void run(){
    
    
          //这里写你的方法
          log.info("开启线程..");
      }
  });
}

二、用ThreadPoolExecutor创建线程池

//1.创建一个大小为10的线程池
BlockingQueue queue = new LinkedBlockingQueue();
ThreadPoolExecutor executor= new ThreadPoolExecutor(10,Integer.MAX_VALUE,10L, TimeUnit.SECONDS,queue);
//给线程池添加任务
for (int i = 0;i < 10;i++){
    
    
executor.execute(new Runnable() {
    
    
    @Override
      public synchronized void run(){
    
    
          //这里写你的方法
          log.info("开启线程..");
      }
  });
}

从根本上说ExecutorService算是通过ThreadPoolExecutor封装出来的他们的底层其实是一样的

ThreadPoolExecutor需要传参,而ExecutorService有默认值,值需要一个线程数量就可以了。

三、用ThreadPoolUtils工具类创建线程池

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

/**
 * 自定义线程创建工具类,创建线程池后不需要关闭
 *
 * @author liangxn
 */
public class ThreadPoolUtils {
    
    
    private static final Logger LOGGER = LoggerFactory.getLogger(ThreadPoolUtils.class);
    private static ThreadPoolExecutor threadPool = null;
    private static final String POOL_NAME = "myPool";
    // 等待队列长度
    private static final int BLOCKING_QUEUE_LENGTH = 1000;
    // 闲置线程存活时间
    private static final int KEEP_ALIVE_TIME = 5 * 1000;

    private ThreadPoolUtils() {
    
    
        throw new IllegalStateException("utility class");
    }


    /**
     * 无返回值直接执行
     *
     * @param runnable 需要运行的任务
     */
    public static void execute(Runnable runnable) {
    
    
        getThreadPool().execute(runnable);
    }

    /**
     * 有返回值执行
     * 主线程中使用Future.get()获取返回值时,会阻塞主线程,直到任务执行完毕
     *
     * @param callable 需要运行的任务
     */
    public static <T> Future<T> submit(Callable<T> callable) {
    
    
        return getThreadPool().submit(callable);
    }

    /**
     * 停止线程池所有任务
     * @return
     */
    public static synchronized void shutdownNow() {
    
    
        getThreadPool().shutdownNow();
    }

    /**
     * 获取线程池中活跃线程数
     * @return
     */
    public static int getActiveCount() {
    
    
        return getThreadPool().getActiveCount();
    }


    private static synchronized ThreadPoolExecutor getThreadPool() {
    
    
        if (threadPool == null) {
    
    
            // 获取处理器数量
            int cpuNum = Runtime.getRuntime().availableProcessors();
            // 根据cpu数量,计算出合理的线程并发数
            int maximumPoolSize = cpuNum * 2 + 1;
            // 核心线程数、最大线程数、闲置线程存活时间、时间单位、线程队列、线程工厂、当前线程数已经超过最大线程数时的异常处理策略
            threadPool = new ThreadPoolExecutor(maximumPoolSize - 1,
                    maximumPoolSize,
                    KEEP_ALIVE_TIME,
                    TimeUnit.MILLISECONDS,
                    new LinkedBlockingDeque<>(BLOCKING_QUEUE_LENGTH),
                    new ThreadFactoryBuilder().setNameFormat(POOL_NAME + "-%d").build(),
                    new ThreadPoolExecutor.AbortPolicy() {
    
    
                        @Override
                        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
    
    
                            LOGGER.warn("线程爆炸了,当前运行线程总数:{},活动线程数:{}。等待队列已满,等待运行任务数:{}",
                                    e.getPoolSize(),
                                    e.getActiveCount(),
                                    e.getQueue().size());
                        }
                    });

        }
        return threadPool;
    }
}

猜你喜欢

转载自blog.csdn.net/xukaiqiang123/article/details/131535153