线程池

池化技术

程序的运行,本质上是占有系统的资源!所以要优化资源的使用=》池化技术

**池化技术:**提前准备好一些资源,又线程来用,就拿给他,用完之后再还给线程池。
线程池的好处

  • 降低资源的消耗:通过重复利用已经创建好的线程降低线程的创建和销毁造成的消耗。
  • 提高响应的速度:当任务达到时,任务可以不需要等到线程创建就能立即执行。
  • 方便管理

线程复用,可以控制最大并发数,管理线程

线程池 : 3大方法 7大参数,4种策略
在这里插入图片描述
1

/**
 * Executors 工具类、三大方法
 * 使用线程池之后,用线程池来创建线程。
 */
public class Demo {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程池 ,只有一个线程操作
       // ExecutorService threadPool = Executors.newFixedThreadPool(5);//创建一个固定大小的线程池,最高可以有五个线程同时执行
        //ExecutorService threadPool = Executors.newCachedThreadPool();//可伸缩的,遇强则强,遇弱则弱。创建多少线程,就有多少线程同时执行

        for(int i=0;i<30;i++){
            threadPool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
            });
        }
        threadPool.shutdown();


    }
}

7大参数

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,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

本质上调用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.acc = System.getSecurityManager() == null ?
            null :
            AccessController.getContext();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

手动创建线程池

ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
        2,//核心大小
        5,//最大进程数
        3,//超时等待
        TimeUnit.SECONDS,//
        new LinkedBlockingDeque<>(3),//空闲容量
        Executors.defaultThreadFactory(),
        //new ThreadPoolExecutor.AbortPolicy()// 线程池满了,还有人进来,不处理这个人并且抛出异常
        //new ThreadPoolExecutor.CallerRunsPolicy()//从哪来,回哪去。main发出,main执行
        //new ThreadPoolExecutor.DiscardPolicy()// 队列满了,丢掉任务,不抛出异常
        new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试去和最早的竞争,如果失败就抛弃,成功就执行。也不会抛弃异常
);
//最大承载=max+capacity

四种拒绝策略

new ThreadPoolExecutor.AbortPolicy()// 线程池满了,还有人进来,不处理这个人并且抛出异常
new ThreadPoolExecutor.CallerRunsPolicy()//从哪来,回哪去。main发出,main执行
new ThreadPoolExecutor.DiscardPolicy()// 队列满了,丢掉任务,不抛出异常
new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试去和最早的竞争,如果失败就抛弃,成功就执行。也不会抛弃异常
// 线程池的大小如何设置?
//1.CPU 密集型    几核CPU就是几个进程数,保持CPU效率最高
//2.I/O 密集型     判断你程序中十分耗I/O的线程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值