【线程池】线程池(一)-七个参数详解

学而不思则罔,思而不学则殆


总结

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
                              ...
                              }
参数解释说明
corePoolSize线程池核心线程大小
maximumPoolSize池中允许的最大线程数
keepAliveTime
unit
workQueue
threadFactory
handler

参数详解

corePoolSize

     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set

线程池中会维护一个最小的线程数量,即使这些线程处理空闲状态,他们也不会被销毁,除非设置了allowCoreThreadTimeOut。这里的最小线程数量即是corePoolSize。

定义一个corePoolSize =1的一个线程池:
在这里插入图片描述
运行两个线程:

        executor.execute(() -> {
            System.out.println(Thread.currentThread().getName());
        });

        executor.execute(() -> {
            System.out.println(Thread.currentThread().getName());
        });

查看核心线程个数:

println("corePoolSize:" + executor.getCorePoolSize());

展示的结果:

pool-1-thread-1
pool-1-thread-2
corePoolSize:1
poolSize:1
activeCount:0

而且两个线程运行结束以后核心线程一直在运行,程序也没有停止。
通过jstack查看线程运行状态:
在这里插入图片描述
发现【pool-1-thread-2】这个线程被park,处于WAITING状态,此时等待新的任务加进来复用这个线程。

当我们设置:
在这里插入图片描述
时候:
线程池的两个任务运行结束后,10s没有添加新任务,线程池的线程都停止了,包括核心线程:
在这里插入图片描述
这里虽然核心线程的个数等于1,实际是没有运行中的线程的。通过jstack命令查看,也找不到线程池相关的线程处于非死亡状态的。

maximumPoolSize - 池中允许的最大线程数

     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool

一个任务被提交到线程池后,首先会缓存到工作队列(后面会介绍)中,如果工作队列满了,则会创建一个新线程,然后从工作队列中的取出一个任务交由新线程来处理,而将刚提交的任务放入工作队列。线程池不会无限制的去创建新线程,它会有一个最大线程数量的限制,这个数量即由maximunPoolSize来指定。

keepAliveTime 空闲线程存活时间

     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.

当线程数量大于核心时,这是多余空闲线程在终止前等待新任务的最大时间。

一个线程如果处于空闲状态,并且当前的线程数量大于corePoolSize,那么在指定时间后,这个空闲线程会被销毁,这里的指定时间由keepAliveTime来设定(如果没新的任务来使用它的话)

unit 空闲线程存活时间单位

空间线程存活时间单位:
在这里插入图片描述

NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS

workQueue 工作队列

新任务被提交后,会先进入到此工作队列中,任务调度时再从队列中取出任务。

原生提供了四种工作队列:

工作队列总结

队列说明补充
LinkedBlockingQuene任务个数无上限,maximumPoolSize 无效
ArrayBlockingQueue任务数量达到corePoolSize放到队列尾,数量达到maximumPoolSize 执行拒绝策略会抛出异常,注意捕获
SynchronousQuene有可用线程,直接加入,没有可以用线程执行拒绝策略会抛出异常,注意捕获
PriorityBlockingQueue任务个数无上限, maximumPoolSize 无效

LinkedBlockingQuene

基于链表的无界阻塞队列(其实最大容量为Interger.MAX),按照FIFO排序。由于该队列的近似无界性,当线程池中线程数量达到corePoolSize后,再有新任务进来,会一直存入该队列,而不会去创建新线程直到maxPoolSize,因此使用该工作队列时,参数maxPoolSize其实是不起作用的。

Java原生代码中单线程池采用了这个工作队列,
在这里插入图片描述
小测试:
先系统单线程池的基础上把maximumPoolSize 线程数改为2,往线程池中加入三个任务:

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(), createFactory("zy", false));

测试结果如下:

1600387430806 : corePoolSize:1
1600387430806 : poolSize:1
1600387430806 : activeCount:1
1600387430806 : MaximumPoolSize:2
1600387430806 : Queue().size:2

当前只有一个线程在运行即核心线程池,MaximumPoolSize没有生效,队列中有两个任务处于等待执行的状态。

ArrayBlockingQueue

基于数组的有界阻塞队列,按FIFO排序。新任务进来后,会放到该队列的队尾,有界的数组可以防止资源耗尽问题。当线程池中线程数量达到corePoolSize后,再有新任务进来,则会将任务放入该队列的队尾,等待被调度。如果队列已经是满的,则创建一个新线程,如果线程数量已经达到maxPoolSize,则会执行拒绝策略。
测试:
添加一个ArrayBlockingQueue个数为1的工作队列。

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2,
            0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(1), createFactory("zy-pool", false));

加入三个任务:
结果如下:

zy-pool-0
zy-pool-1
zy-pool-0
zy-pool-1
1600388335424 : corePoolSize:1
1600388335424 : poolSize:2
1600388335424 : activeCount:2
1600388335424 : MaximumPoolSize:2
1600388335424 : Queue().size:1

共有两个任务线程在执行,队列中有一个任务在等待。

加入四个任务:
结果如下:
在这里插入图片描述

zy-pool-0
zy-pool-1
1600388450495 : corePoolSize:1
1600388450495 : poolSize:2
1600388450495 : activeCount:2
1600388450495 : MaximumPoolSize:2
1600388450496 : Queue().size:1
1600388450496 : ---
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task com.thread.ThreadPoolDemo$$Lambda$6/1531448569@6f496d9f rejected from java.util.concurrent.ThreadPoolExecutor@723279cf[Running, pool size = 2, active threads = 2, queued tasks = 1, completed tasks = 0]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
	at com.thread.ThreadPoolDemo.main(ThreadPoolDemo.java:96)

抛出了异常,采用的AbortPolicy 拒绝策略。但是呢之前加入的任务还是在正常执行。

SynchronousQuene

一个不缓存任务的阻塞队列,生产者放入一个任务必须等到消费者取出这个任务。也就是说新任务进来时,不会缓存,而是直接被调度执行该任务,如果没有可用线程,则创建新线程,如果线程数量达到maxPoolSize,则执行拒绝策略。
小测试:

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2,
            0L, TimeUnit.MILLISECONDS,
            new SynchronousQueue<Runnable>(), createFactory("zy-pool", false));

添加四个任务,结果如下:
在这里插入图片描述

java.util.concurrent.RejectedExecutionException: Task com.thread.ThreadPoolDemo$$Lambda$3/2065951873@3feba861 rejected from java.util.concurrent.ThreadPoolExecutor@5b480cf9[Running, pool size = 2, active threads = 2, queued tasks = 0, completed tasks = 0]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
	at com.thread.ThreadPoolDemo.addTask(ThreadPoolDemo.java:53)
	at com.thread.ThreadPoolDemo.main(ThreadPoolDemo.java:45)
java.util.concurrent.RejectedExecutionException: Task com.thread.ThreadPoolDemo$$Lambda$3/2065951873@3feba861 rejected from java.util.concurrent.ThreadPoolExecutor@5b480cf9[Running, pool size = 2, active threads = 2, queued tasks = 0, completed tasks = 0]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
	at com.thread.ThreadPoolDemo.addTask(ThreadPoolDemo.java:53)
	at com.thread.ThreadPoolDemo.main(ThreadPoolDemo.java:46)
zy-pool-0
zy-pool-1
zy-pool-0
zy-pool-1
1600388791331 : corePoolSize:1
1600388791331 : poolSize:2
1600388791331 : activeCount:2
1600388791331 : MaximumPoolSize:2
1600388791331 : Queue().size:0

运行中的任务有两个,等于MaximumPoolSize=2,队列中没有任务,个数为0.

PriorityBlockingQueue

具有优先级的无界阻塞队列,优先级通过参数Comparator实现。
小测试:

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2,
            0L, TimeUnit.MILLISECONDS,
            new PriorityBlockingQueue<Runnable>(1, new Comparator<Runnable>() {
                @Override
                public int compare(Runnable o1, Runnable o2) {
                    return 0;
                }
            }), createFactory("zy-pool", false));

添加4个任务:

zy-pool-0
zy-pool-0
zy-pool-0
1600389180074 : corePoolSize:1
1600389180074 : poolSize:1
1600389180074 : activeCount:1
1600389180074 : MaximumPoolSize:2
1600389180074 : Queue().size:3
1600389180074 : ---
zy-pool-0
zy-pool-0

有一个任务,corePoolSize=1 在执行,MaximumPoolSize不生效,队列中有3个任务在等待

threadFactory 线程工厂

创建一个新线程时使用的工厂,可以用来设定线程名、是否为daemon线程等等
可以采用默认的,也是自定义实现:

自定义实现:

    private static ThreadFactory createFactory(final String name, boolean daemon) {
        AtomicInteger atomicInteger = new AtomicInteger();
        return (r) -> {
            Thread thread = new Thread(r, name + "-" + atomicInteger.getAndIncrement());
            thread.setDaemon(daemon);
            return thread;
        };
    }

提供的默认工厂:

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              RejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), handler);
    }
    
    public static ThreadFactory defaultThreadFactory() {
        return new DefaultThreadFactory();
    }
    
    static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

不设置自己的线程工厂的时候,一般是采取默认的工厂。

handler 拒绝策略

当工作队列中的任务已到达最大限制,并且线程池中的线程数量也达到最大限制,这时如果有新任务提交进来,该如何处理呢。这里就拒绝策略干的事;

拒绝策略的是一个接口,默认有四种实现对应四种策略:

public interface RejectedExecutionHandler {
    void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}

在这里插入图片描述

默认拒绝策略总结

子类策略异常
AbortPolicy直接抛弃抛出异常
CallerRunsPolicy如果线程池没有shutdown,在调用者线程中直接执行被拒绝任务的run方法,否则抛弃任务不抛出异常
DiscardOldestPolicy抛弃进入队列最早的那个任务,然后尝试把这次拒绝的任务放入队列不抛出异常
DiscardPolicy直接丢弃任务,什么都不做不抛出异常

AbortPolicy

该策略下,直接丢弃任务,并抛出RejectedExecutionException异常。

    /**
     * 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 r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         * @throws RejectedExecutionException always
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
    }

CallerRunsPolicy

该策略下,在调用者线程中直接执行被拒绝任务的run方法,除非线程池已经shutdown,则直接抛弃任务,不抛出异常。

    /**
     * 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();
            }
        }
    }

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);
            }
        }
    }

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) {
        }
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值