ThreadPoolExecutor自定义线程池

1.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; }

参数简介:

- corePoolSize:核心线程数量

- maximumPoolSize:最大线程数量

- keepAliveTime:没有执行任务的线程,最大空闲时间

- unit:时间单位,TimeUnit.DAYS,TimeUnit.HOURS,TimeUnit.MINUTES,TimeUnit.SECONDS,TimeUnit.MILLISECONDS
			TimeUnit.MICROSECONDS,TimeUnit.NANOSECONDS,七种

- BlockingQueue<Runnable> workQueue:一个阻塞队列,用来存储等待执行的任务,
			ArrayBlockingQueue,LinkedBlockingQueue,SynchronousQueue三种

- ThreadFactory threadFactory:创建线程的工厂类

- RejectedExecutionHandler handler:拒绝策略

2.拒绝策略 拒绝策略: 四种拒绝策略,实现:RejectedExecutionHandler接口 1.AbortPolicy(中止策略,抛出异常,默认的策略)

源码: /** * A handler for rejected tasks that throws a * {@code RejectedExecutionException}. / public static class AbortPolicy implements RejectedExecutionHandler { /* * Creates an {@code AbortPolicy}. */ public AbortPolicy() { }

    /**
     * Always throws RejectedExecutionException.
     *
     * [@param](https://my.oschina.net/u/2303379) r the runnable task requested to be executed
     * [@param](https://my.oschina.net/u/2303379) e the executor attempting to execute this task
     * [@throws](https://my.oschina.net/throws) RejectedExecutionException always
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        throw new RejectedExecutionException("Task " + r.toString() +
                                             " rejected from " +
                                             e.toString());
    }
}

2.CallerRunsPolicy(由调用线程处理该任务)

源码: /** * A handler for rejected tasks that runs the rejected task * directly in the calling thread of the {@code execute} method, * unless the executor has been shut down, in which case the task * is discarded. / public static class CallerRunsPolicy implements RejectedExecutionHandler { /* * Creates a {@code CallerRunsPolicy}. */ public CallerRunsPolicy() { }

    /**
     * Executes task r in the caller‘s thread, unless the executor
     * has been shut down, in which case the task is discarded.
     *
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        if (!e.isShutdown()) {
            r.run();
        }
    }
}

3.DiscardOldestPolicy(丢弃队列最前面的任务,然后重新提交被拒绝的任务)

源码: /** * A handler for rejected tasks that discards the oldest unhandled * request and then retries {@code execute}, unless the executor * is shut down, in which case the task is discarded. / public static class DiscardOldestPolicy implements RejectedExecutionHandler { /* * Creates a {@code DiscardOldestPolicy} for the given executor. */ public DiscardOldestPolicy() { }

    /**
     * Obtains and ignores the next task that the executor
     * would otherwise execute, if one is immediately available,
     * and then retries execution of task r, unless the executor
     * is shut down, in which case task r is instead discarded.
     *
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        if (!e.isShutdown()) {
            e.getQueue().poll();
            e.execute(r);
        }
    }
}

4.DiscardPolicy(丢弃任务,但是不抛出异常。如果线程队列已满,则后续提交的任务都会被丢弃,且是静默丢弃)

源码: /** * A handler for rejected tasks that silently discards the * rejected task. / public static class DiscardPolicy implements RejectedExecutionHandler { /* * Creates a {@code DiscardPolicy}. */ public DiscardPolicy() { }

    /**
     * Does nothing, which has the effect of discarding task r.
     *
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
    }
}

根据实际需求,制定合适的拒绝策略

来源:江苏网站优化

原文地址:https://www.cnblogs.com/1994july/p/12080393.html

时间: 2024-10-17 15:47:48

ThreadPoolExecutor自定义线程池的相关文章

Android线程管理之ThreadPoolExecutor自定义线程池(三)

前言: 上篇主要介绍了使用线程池的好处以及ExecutorService接口,然后学习了通过Executors工厂类生成满足不同需求的简单线程池,但是有时候我们需要相对复杂的线程池的时候就需要我们自己来自定义一个线程池,今天来学习一下ThreadPoolExecutor,然后结合使用场景定义一个按照线程优先级来执行的任务的线程池. ThreadPoolExecutor ThreadPoolExecutor线程池用于管理线程任务队列.若干个线程. 1.)ThreadPoolExecutor构造函数

基于ThreadPoolExecutor,自定义线程池简单实现

一.线程池作用 在上一篇随笔中有提到多线程具有同一时刻处理多个任务的特点,即并行工作,因此多线程的用途非常广泛,特别在性能优化上显得尤为重要.然而,多线程处理消耗的时间包括创建线程时间T1.工作时间T2.销毁线程时间T3,创建和销毁线程需要消耗一定的时间和资源,如果能够减少这部分的时间消耗,性能将会进一步提高,线程池就能够很好解决问题.线程池在初始化时会创建一定数量的线程,当需要线程执行任务时,从线程池取出线程,当任务执行完成后,线程置回线程池成为空闲线程,等待下一次任务.JDK1.5提供了一个

自定义线程池的名称(ThreadPoolExecutor)

目的:有时候为了快速定位出现错误的位置,在采用线程池时我们需要自定义线程池的名称. 1.创建ThreadFactory(ThreadPoolExecutor默认采用的是DefaultThreadFactory,可以参照代码). public class NamedThreadFactory implements ThreadFactory{ private final AtomicInteger poolNumber = new AtomicInteger(1); private final T

java多线程(四)-自定义线程池

当我们使用 线程池的时候,可以使用 newCachedThreadPool()或者 newFixedThreadPool(int)等方法,其实我们深入到这些方法里面,就可以看到它们的是实现方式是这样的. 1 public static ExecutorService newCachedThreadPool() { 2 return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 3 60L, TimeUnit.SECONDS, 4 new Synchro

Java自定义线程池详解

自定义线程池的核心:ThreadPoolExecutor 为了更好的控制多线程,JDK提供了一套线程框架Executor,帮助开发人员有效的进行线程控制,其中在java.util.concurrent包下,是JDK并发包的核心,比如我们熟知的Executors.Executors扮演着线程工厂的角色,我们通过它可以创建特定功能的线程池,而这些线程池背后的就是:ThreadPoolExecutor.那么下面我们来具体分析下它. 构造ThreadPoolExecutor public ThreadP

JAVA并发,线程工厂及自定义线程池

1 package com.xt.thinks21_2; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 import java.util.concurrent.SynchronousQueue; 6 import java.util.concurrent.ThreadFactory; 7 import java.util.concurrent.ThreadPo

Java 自定义线程池

Java 自定义线程池 https://www.cnblogs.com/yaoxiaowen/p/6576898.html public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandle

springboot中使用自定义线程池ThreadPoolTaskExecutor

java5以后,线程有了很大的变化,在使用上更加方便功能更佳强大,Springboot里面进行了进一步的封装. 我们来看一个例子 package com.executor; import java.util.concurrent.Executor;import java.util.concurrent.RejectedExecutionHandler;import java.util.concurrent.ThreadPoolExecutor; import org.springframewor

池化技术——自定义线程池

目录 池化技术--自定义线程池 1.为什么要使用线程池? 1.1.池化技术的特点: 1.2.线程池的好处: 1.3.如何自定义一个线程池 2.三大方法 2.1.单个线程的线程池方法 2.2.固定的线程池的大小的方法 2.3.可伸缩的线程池的方法 2.4.完整的测试代码为: 3.为什么要自定义线程池?三大方法创建线程池的弊端分析 4.七大参数 5.如何手动的去创建一个线程池 6.四种拒绝策略 6.1.会抛出异常的拒绝策略 6.2.哪来的去哪里拒绝策略 6.3.丢掉任务拒绝策略 6.4.尝试竞争拒绝