线程池(三大方法,七大参数,四种拒绝策略)

线程池(三大方法,七大参数,四种拒绝策略)

池化技术

程序的本质:占用系统的资源,优化资源使用==》池化技术

池化技术:实现准备好一些资源,有人要用,从池里拿,用完后放回池里

线程池的优势

  1. 减低资源的消耗

  2. 提高响应速度

  3. 方便管理

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

三大方法

package ex3;
​
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
​
/*
* Executor 工具类 三大方法
* */
public class demo1 {
    public static void main(String[] args) {
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程
//        ExecutorService threadPool = Executors.newFixedThreadPool(5);//创建一个固定大小的线程池
        ExecutorService threadPool = Executors.newCachedThreadPool();//可伸缩的,遇强则强,遇弱则弱
        try {
            for (int i = 0; i < 100; i++) {
                //使用线程池后,用线程创建线程
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+":ok");
                });
            }
        } 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,//21亿
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
​
  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;
    }

手动创建线程池

四大拒绝策略

* new ThreadPoolExecutor.AbortPolicy ());//队列满了 抛出异常
* new ThreadPoolExecutor.CallerRunsPolicy ());//哪来的去哪里  -main线程执行
*  new ThreadPoolExecutor.DiscardOldestPolicy ());//队列满了 尝试与最早的竞争
*  new ThreadPoolExecutor.DiscardPolicy ());//队列满了 不会抛出异常package ex3;
​
import java.util.concurrent.*;
/*
* Executor 工具类 三大方法
* new ThreadPoolExecutor.AbortPolicy ());//队列满了 抛出异常
* new ThreadPoolExecutor.CallerRunsPolicy ());//哪来的去哪里
*  new ThreadPoolExecutor.DiscardOldestPolicy ());//队列满了 尝试与最早的竞争
*  new ThreadPoolExecutor.DiscardPolicy ());//队列满了 不会抛出异常
* */
public class demo2 {
    public static void main(String[] args) {
//        自定义线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 5, 3,
                TimeUnit.SECONDS, new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy ());//队列满了 抛出异常
        try {
//            最大承载 deque+ max
            for (int i = 1; i <=10; i++) {
                //使用线程池后,用线程创建线程
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+":ok");
                });
            }
        } finally {
//            使用线程池后需要关闭
            threadPool.shutdown();
        }
​
​
    }
}
​

最大线程如何定义 1.cup密集型 :

几核就定几 效率最高 ​ 2.IO密集型 :

最大线程>判断你的程序中十分耗费io的线程的个数

获取cup的核数

  • Runtime.getRuntime().availableProcessors()//获取cup的核数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值