线程池(重点)

1.线程池的三大方法

package com.kuang.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//Executors工具类  三大方法
//使用线程池,创建线程
public class Demo01 {
    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");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }



    }
}

2.源码分析

2.1 newSingleThreadExecutor() 

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

2.2 newFixedThreadPool(int nThreads)

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

2.3 newCachedThreadPool()

  public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
本质是:new 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;
    }
public ThreadPoolExecutor(int corePoolSize,//核心线程池大小
                          int maximumPoolSize,//最大核心线池大小
                          long keepAliveTime,//超时了没有人调用就会释放
                          TimeUnit unit,//超时单位
                          BlockingQueue<Runnable> workQueue,//阻塞队列
                          ThreadFactory threadFactory,//线程工厂,创建线程的,一般不用动
                          RejectedExecutionHandler handler) {// 拒绝策略
 

 手动 创建一个线程池 

       new

4种拒绝策略

package com.kuang.pool;

import java.security.AccessController;
import java.util.concurrent.*;

import static java.util.concurrent.Executors.newSingleThreadExecutor;

//Executors工具类  三大方法
//使用线程池,创建线程

/**
 * 第一种拒绝策略  new ThreadPoolExecutor.AbortPolicy() 超出,则不去执行那个多的,而且会抛异常RejectedExecutionException
 * 第二种拒绝策略 new ThreadPoolExecutor.CallerRunsPolicy() 哪个线程的创建出的这个线程,就回到哪个线程去执行
 *  第三种拒绝策略  new ThreadPoolExecutor.DiscardPolicy() 队列满了 丢掉任务, 不去执行,也不抛异常
 * 第四种拒绝策略 new ThreadPoolExecutor.DiscardOldestPolicy()   队列满了,会抛弃任务队列中最旧的任务也就是最先加入队列的,再把这个新任务添加进去。也不会抛异常!!!
 *
 */
public class Demo01 {
    public static void main(String[] args) {
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程。
       //ExecutorService threadPool = Executors.newFixedThreadPool(5);// 创建一个固定的线程池的大小。阻塞队列无线大,创建线程固定
//        ExecutorService threadPool = Executors.newCachedThreadPool();//创建一个可伸缩的,遇强则强,遇弱则弱。 创建线程无线大,阻塞队列就一个容量
        ExecutorService threadPool = new ThreadPoolExecutor(2
                , 5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()//银行满了,还有人进来,不处理这个人的,抛出异常.
        );

        try {
            //最大承载: Deque+max =5+3=8
            //超过 RejectedExecutionException
            for (int i =1; i <=9; i++) {
                int finalI = i;
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+" ok"+ finalI);
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }



    }





}

3. 最大线程到底该如何定义(调优)

1、CPU密集型  CPU的内核为几, 最大线程就定义为几,可以保持CPU的效率最高!

代码获取CPU的核数 

System.out.println("CPU核心为:"+Runtime.getRuntime().availableProcessors());

2、IO密集型  判断 你程序中十分耗IO的线程  就把最大线程定义 >15   比如

程序 15 个大型任务,io十分占用资源,就设置最大线程定义为30

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值