您当前的位置:首页 > 计算机 > 编程开发 > Java

Java 线程池相关知识点

时间:12-14来源:作者:点击数:

八种线程池创建方式

ExecutorService threadPool = Executors.newSingleThreadExecutor(); // 单线程的线程池,只有一个线程在工作

ExecutorService threadPool = Executors.newSingleThreadScheduledExecutor(); // 单线程的线程池,只有一个线程在工作

ExecutorService threadPool = Executors.newCachedThreadPool(); // 有缓冲的线程池,线程数 JVM 控制

ExecutorService threadPool = Executors.newFixedThreadPool(3); // 固定大小的线程池

ExecutorService threadPool = Executors.newScheduledThreadPool(2);

ExecutorService threadPool = Executors.newWorkStealingPool(2);

两种底层实现

ExecutorService threadPool = new ThreadPoolExecutor(); // 默认线程池,可控制参数比较多

ExecutorService threadPool = new ForkJoinPool(); // newWorkStealingPool 的底层实现

三种阻塞队列

BlockingQueue workQueue workQueue = new ArrayBlockingQueue<>(5); // 基于数组的先进先出队列,有界

BlockingQueue workQueue workQueue = new LinkedBlockingQueue<>(); // 基于链表的先进先出队列,无界

BlockingQueue workQueue workQueue = new SynchronousQueue<>(); // 无缓冲的等待队列,无界

SynchronousQueue

SynchronousQueue 没有容量,是无缓冲等待队列,是一个不存储元素的阻塞队列,会直接将任务交给消费者,必须等队列中的添加元素被消费后才能继续添加新的元素。 拥有公平(FIFO)和非公平(LIFO)策略,非公平侧罗会导致一些数据永远无法被消费的情况? 使用 SynchronousQueue 阻塞队列一般要求 maximumPoolSizes 为无界,避免线程拒绝执行操作。

LinkedBlockingQueue

LinkedBlockingQueue 是一个无界缓存等待队列。当前执行的线程数量达到 corePoolSize 的数量时,剩余的元素会在阻塞队列里等待。(所以在使用此阻塞队列时maximumPoolSizes 就相当于无效了),每个线程完全独立于其他线程。生产者和消费者使用独立的锁来控制数据的同步,即在高并发的情况下可以并行操作队列中的数据。

ArrayBlockingQueue

ArrayBlockingQueue 是一个有界缓存等待队列,可以指定缓存队列的大小,当正在执行的线程数等于 corePoolSize 时,多余的元素缓存在 ArrayBlockingQueue 队列中等待有空闲的线程时继续执行,当 ArrayBlockingQueue 已满时,加入 ArrayBlockingQueue 失败,会开启新的线程去执行,当线程数已经达到最大的 maximumPoolSizes 时,再有新的元素尝试加入 ArrayBlockingQueue 时会报错。

四种拒绝策略

RejectedExecutionHandler rejected = new ThreadPoolExecutor.AbortPolicy(); // 默认,队列满了丢任务抛出异常

RejectedExecutionHandler rejected = new ThreadPoolExecutor.DiscardPolicy(); // 队列满了丢任务不异常

RejectedExecutionHandler rejected = new ThreadPoolExecutor.DiscardOldestPolicy(); // 将最早进入队列的任务删,之后再尝试加入队列

RejectedExecutionHandler rejected = new ThreadPoolExecutor.CallerRunsPolicy(); // 如果添加到线程池失败,那么主线程会自己去执行该任务

同一个世界同一个梦想

java.util.concurrent.ThreadPoolExecutor.execute

java.util.concurrent.ForkJoinPool.execute

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐