线程池应用

作用

为了方便控制线程的数量

线程池的原理
  • 线程池管理器:用于创建并管理线程池,包括创建线程池,销毁线程池,添加新任务
  • 工作线程:线程池中线程,在没有任务的时候处于等待状态,可以循环的执行任务
  • 任务接口:每个任务必须实现的借口,以提供工作仙尘调度任务的执行,它主要规定了任务的入口,任务执行完成后的首位工作,任务的执行状态等
  • 任务队列:用于存放没有处理的任务,提供一种缓存机制在这里插入图片描述
线程池API

在这里插入图片描述

ExecutorService

在这里插入图片描述

API测试Demo
package com.hzw;

import java.util.List;
import java.util.concurrent.*;

public class Demo6 {
    public static void main(String[] args) throws Exception {
        Demo6 demo6 = new Demo6();
//        demo6.threadPoolExecutorTest1();
//        demo6.threadPoolExecutorTest2();
//        demo6.threadPoolExecutorTest3();
//        demo6.threadPoolExecutorTest4();
//        demo6.threadPoolExecutorTest();
//        demo6.threadPoolExecutorTest6();
//        demo6.threadPoolExecutorTest7();
        demo6.threadPoolExecutorTest8();
    }

    /**
     * 线程池信息:核心线程数量为5,最大数量为10,无界队列,超出核心线程数量的线程存活时间为5秒
     * 当任务队列为无界时,最大线程数量设置便失去意义,
     * 因为只有当任务队列满了以后才会在核心线程数的基础上重新开启新的线程,知道达到最大线程数量为止
     * @throws InterruptedException
     */
    private void threadPoolExecutorTest1() throws InterruptedException {
        //参数以此为:核心线程数、最大线程数量、超出核心线程数的线程的存活时间、时间参数的单位、任务队列
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 5, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>());
        testCommon(threadPoolExecutor);
    }

    /**
     * 线程池信息:核心线程数量为5,最大数量为10,任务队列大小5,超出核心线程数量的线程存活时间为5秒,指定拒绝策略
     * @throws InterruptedException
     */
    private void threadPoolExecutorTest2() throws InterruptedException {
        //参数以此为:核心线程数、最大线程数量、超出核心线程数的线程的存活时间、时间参数的单位、任务队列、超出部分任务的拒绝策略
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 5, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3), new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                System.err.println("有任务被拒绝执行了");
            }
        });
        testCommon(threadPoolExecutor);
    }

    /**
     * 线程池信息:核心线程数量为5,最大数量为10,任务队列大小5,超出核心线程数量的线程存活时间为5秒,不指定拒绝策略
     * 默认的策略是抛出RejectedExecutionException异常,需要进行相应的异常捕获
     * @throws InterruptedException
     */
    private void threadPoolExecutorTest3() throws InterruptedException {
        //参数以此为:核心线程数、最大线程数量、超出核心线程数的线程的存活时间、时间参数的单位、任务队列、超出部分任务的拒绝策略
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 5, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3));
        testCommon(threadPoolExecutor);
    }

    /**
     * 线程池信息:核心线程数量:0,最大数量:Integer.MAX_VALUE,任务队列:SynchronousQueue队列,超出核心线程数量的线程存活时间:60秒
     * 这种情况下核心线程数为0,所以一旦有任务过来切没有空闲的线程就会新开一个线程,新开线程超过60秒没有工作就会被关闭
     * SynchronousQueue队列(同步队列):实际上不是一个真正的队列,因为它不会为队列中的元素维护储存空间。与其他队列不同的是,他维护一组线程,这组线程在等待着把元素加入或移除队列
     * @throws InterruptedException
     */
    private void threadPoolExecutorTest4() throws InterruptedException {
        //等价于:Executors.newCachedThreadPool()
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
                new SynchronousQueue<>());
        testCommon(threadPoolExecutor);
        Thread.sleep(60000L);
        System.out.println("60秒后,再看线程池中的线程数量:" + threadPoolExecutor.getPoolSize());
    }

    /**
     * 定时执行线程池信息:3秒后执行,一次性任务,到点就执行 <br/>
     * 核心线程数量5,最大数量Integer.MAX_VALUE,DelayedWorkQueue延时队列,超出核心线程数量的线程存活时间:0秒
     */
    private void threadPoolExecutorTest() {
        //等价于:Executors.newScheduledThreadPool()
        ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(5);
        threadPoolExecutor.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务被执行,现在时间:" + System.currentTimeMillis());
            }
        }, 3000, TimeUnit.MILLISECONDS);
        System.out.println(
                "定时任务,提交成功,时间是:" + System.currentTimeMillis() + ", 当前线程池中线程数量:" + threadPoolExecutor.getPoolSize());
    }

    /**
     * 6、 定时执行线程池信息:线程固定数量5 ,<br/>
     * 核心线程数量5,最大数量Integer.MAX_VALUE,DelayedWorkQueue延时队列,超出核心线程数量的线程存活时间:0秒
     *
     * @throws Exception
     */
    private void threadPoolExecutorTest6() throws Exception {
        ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(5);
        // 效果1: 提交后,2秒后开始第一次执行,之后每间隔1秒,固定执行一次(如果发现上次执行还未完毕,则等待完毕,完毕后立刻执行)。
        // 也就是说这个代码中是,3秒钟执行一次(计算方式:每次执行三秒,间隔时间1秒,执行结束后马上开始下一次执行,无需等待)
        threadPoolExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("任务-1 被执行,现在时间:" + System.currentTimeMillis());
            }
        }, 2000, 1000, TimeUnit.MILLISECONDS);

        // 效果2:提交后,2秒后开始第一次执行,之后每间隔1秒,固定执行一次(如果发现上次执行还未完毕,则等待完毕,等上一次执行完毕后再开始计时,等待1秒)。
        // 也就是说这个代码钟的效果看到的是:4秒执行一次。 (计算方式:每次执行3秒,间隔时间1秒,执行完以后再等待1秒,所以是 3+1)
        threadPoolExecutor.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("任务-2 被执行,现在时间:" + System.currentTimeMillis());
            }
        }, 2000, 1000, TimeUnit.MILLISECONDS);
    }


    /**
     * 7、 终止线程:线程池信息: 核心线程数量5,最大数量10,队列大小3,超出核心线程数量的线程存活时间:5秒, 指定拒绝策略的
     *
     * 结果分析
     * 1、10个任务被执行,3个任务进入队列等待,2个任务被拒绝执行
     * 2、调用shutdown后,不接收新的任务,等待13任务执行结束
     * 3、追加的任务在线程池关闭后,无法再提交,会被拒绝执行
     * @throws Exception
     */
    private void threadPoolExecutorTest7() throws Exception {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 5, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3), (r, executor) -> System.err.println("有任务被拒绝执行了"));
        // 测试: 提交15个执行时间需要3秒的任务,看超过大小的2个,对应的处理情况
        for (int i = 0; i < 15; i++) {
            int n = i;
            threadPoolExecutor.submit(() -> {
                try {
                    System.out.println("开始执行:" + n);
                    Thread.sleep(3000L);
                    System.err.println("执行结束:" + n);
                } catch (InterruptedException e) {
                    System.out.println("异常:" + e.getMessage());
                }
            });
            System.out.println("任务提交成功 :" + i);
        }
        // 1秒后终止线程池
        Thread.sleep(1000L);
        threadPoolExecutor.shutdown();
        // 再次提交提示失败
        threadPoolExecutor.submit(() -> System.out.println("追加一个任务"));
    }

    /**
     * 8、 立刻终止线程:线程池信息: 核心线程数量5,最大数量10,队列大小3,超出核心线程数量的线程存活时间:5秒, 指定拒绝策略的
     *
     * 结果分析
     * 1、 10个任务被执行,3个任务进入队列等待,2个任务被拒绝执行
     * 2、 调用shutdownNow后,队列中的3个线程不再执行,10个线程被终止
     * 3、 追加的任务在线程池关闭后,无法再提交,会被拒绝执行
     * @throws Exception
     */
    private void threadPoolExecutorTest8() throws Exception {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 5, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3), (r, executor) -> System.err.println("有任务被拒绝执行了"));
        // 测试: 提交15个执行时间需要3秒的任务,看超过大小的2个,对应的处理情况
        for (int i = 0; i < 15; i++) {
            int n = i;
            threadPoolExecutor.submit(() -> {
                try {
                    System.out.println("开始执行:" + n);
                    Thread.sleep(3000L);
                    System.err.println("执行结束:" + n);
                } catch (InterruptedException e) {
                    System.out.println("异常:" + e.getMessage());
                }
            });
            System.out.println("任务提交成功 :" + i);
        }
        // 1秒后终止线程池
        Thread.sleep(1000L);
        List<Runnable> shutdownNow = threadPoolExecutor.shutdownNow();
        // 再次提交提示失败
        threadPoolExecutor.submit(() -> System.out.println("追加一个任务"));
        System.out.println("未结束的任务有:" + shutdownNow.size());
    }

    private void testCommon(ThreadPoolExecutor threadPoolExecutor) throws InterruptedException {
        for (int i = 0; i < 15; i++) {
            int n = i;
            threadPoolExecutor.submit(() -> {
                System.out.println("开始执行:" + n);
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.err.println("结束执行:" + n);
            });
            System.out.println("任务提交成功:" + i);
        }
        Thread.sleep(500L);
        System.out.println("当前线程池线程数量为:" + threadPoolExecutor.getPoolSize());
        System.out.println("当前线程池等待数量为:" + threadPoolExecutor.getQueue().size());
        Thread.sleep(15000L);
        System.out.println("当前线程池线程数量为:" + threadPoolExecutor.getPoolSize());
        System.out.println("当前线程池等待数量为:" + threadPoolExecutor.getQueue().size());
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值