创建线程池的方法

创建线程池的方法

一、创建线程池的三种方法

Executors.newSingleThreadExecutor(); //单个线程
Executors.newFixedThreadPool(5); //创建一个固定的线程池
Executors.newCachedThreadPool(); //创建一个可伸缩的线程池

1.newSingleThreadExecutor

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

public class ExecuterTest1 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();  //单个线程
        try {
            for(int i=0;i<10;i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+" ok");
                });
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭线程池
            threadPool.shutdown();
        }

    }
}

2. newFixedThreadPool

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

public class ExecuterTest1 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(5); //创建一个固定的线程池

        try {
            for(int i=0;i<10;i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+" ok");
                });
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭线程池
            threadPool.shutdown();
        }

    }
}

3. newCachedThreadPool

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

public class ExecuterTest1 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();  //创建一个可伸缩的线程池
        try {
            for(int i=0;i<10;i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+" ok");
                });
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭线程池
            threadPool.shutdown();
        }

    }
}

二、三种方法的源码

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

//#############################################################

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

//############################################################

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,  //约等于20亿
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}
  • 以上三种方法中都调用ThreadPoolExecutor来创建线程池。
  • 但三种方法都存在一定的弊端:
  • (1)SingleThreadExecutor和FixedThreadPool允许的请求队列长度为Integer.MAX.VALUE,可能会导致OOM
  • (2)CachedThreadPool允许的创建线程数量为Integer.MAX.VALUE,可能会导致OOM

ThreadPoolExecutor源码分析

    public ThreadPoolExecutor(int corePoolSize,     //核心线程池大小
                              int maximumPoolSize,  //最大核心线程池大小
                              long keepAliveTime,   //超时了没有人调用就会释放
                              TimeUnit unit,   //超时单位
                              BlockingQueue<Runnable> workQueue,   //阻塞队列
                              ThreadFactory threadFactory,        //线程工厂,创建线程的,一般不用动
                              RejectedExecutionHandler handler) {   //拒绝策略
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值