线程池

    线程池的优势:

线程池做的工作主要是控制运行的线程的数量,处理过程中将任务放入队列,然后在线程创建后启动这些任务,如果线程的数量超过最大数量超出数量的线程排队等候,等其他线程执行完毕,再从队列中取出任务来执行。

线程池的特点:线程复用,控制最大并发数,管理线程

一    降低资源消耗

二    提高响应速度

三    提高线程的可管理性

查看底层CPU的核数

System.out.println(Runtime.getRuntime().availableProcessors());

线程池的架构

java中的线程池是通过Executor框架实现的,该框架中用到了Executor,Execut,ExecutorService,ThreadPoolExecutor这几个类。

Executors.newWorkStealingPool(int)->java8新增,使用目前机器上的可用的处理器作为它的并行级别。

多线程的实现方式

第四种获得,使用java多线程的方式,线程池 Executors
* 第一种继承Thread类
* 第二种实现runnable接口,没有返回值,不抛异常
* 第三种实现callable接口,有返回值,会抛出异常

三种线程池的实现方式

ExecutorService executorService= Executors.newFixedThreadPool(5);//一池五个线程
ExecutorService executorService= Executors.newSingleThreadExecutor();//一池一个线程
ExecutorService executorService= Executors.newCachedThreadPool();//一池多线程

线程池的几个重要参数介绍

线程池ThreadPoolExecutor底层的七大参数

5个参数的ThreadPoolExecutor方法

public ThreadPoolExecutor(int corePoolSize, //线程数,相当于银行的开放的窗口数
                          int maximumPoolSize,// 最大的线程数,相当于银行可以开放的最多的窗口数
                          long keepAliveTime,// 多余的空闲线程存活的时间
                          TimeUnit unit,// 空闲的线程可以存活的时间
                          BlockingQueue<Runnable> workQueue)// 阻塞队列,相当于银行的等候大厅

 {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}

7个参数的ThreadPoolExecutor方法

public ThreadPoolExecutor(int corePoolSize,//线程数,相当于银行的开放的窗口数
                          int maximumPoolSize, //最大的线程数,相当于银行可以开放的最多的窗口数
                          long keepAliveTime, //多余的空闲线程存活的时间
                          TimeUnit unit, //空闲的线程可以存活的时间
                          BlockingQueue<Runnable> workQueue, //阻塞队列,相当于银行的等候大厅
                          ThreadFactory threadFactory, //线程工厂,一般用默认的方式,相当于银行的ID标识
                          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;
}

线程池的拒绝策略

JDK内置的4种拒绝策略:

AbortPolicy(默认):直接抛出RejectedExecutionException异常组织系统正常运行

CallerRuncPolicy:“调用者运行”一种调节机制,该策略既不会抛弃任务,也不会抛出异常,而是将某些任务回退到调用者,从而降低新任务的流量。

DiscardOldestPolicy:抛弃队列中等待最久的任务,然后把当前任务加入队列中尝试再次提交当前任务。

DiscardPolicy:直接丢弃任务,不予任何处理也不抛出异常。如果允许任务丢失,这是最好的一种方案。

JDK四种内置拒绝策略均实现了RejectedExecutionHandler接口。

原文地址:https://www.cnblogs.com/yutting/p/11493047.html