Java线程-线程池-自定义线程池

本文介绍了如何在Java中自定义线程池,详细解释了核心参数如corePoolSize、keepAliveTime和maximumPoolSize的限制,并指出可能出现的异常情况,如IllegalArgumentException和NullPointerException。此外,还提及自定义线程池虽然复杂,但能提供对线程池状态的深入监控,如当前尺寸、执行任务的线程数量及工作队列等信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义线程池,代码如下:

public class ThreadExtend_Pool_Custom extends Thread {
    private String name;//线程的名字
    public ThreadExtend_Pool_Custom(String name){
        this.name=name;
    }
    @Override
    public void run(){
        System.out.println(Thread.currentThread().getName()+"正在执行......");
        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]){

        //创建等待队列
        BlockingQueue<Runnable> blockingQueue=new ArrayBlockingQueue<Runnable>(20);

        /**
         * 创建一个单线执行任务,它可安排在给定延迟后运行命令或者定期地执行
         * corePoolSize -池中所保存的线程数,包括空闲线程
         * maximumPoolSize -池中允许的最大线程数
         * keepAliveTime -当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间
         * unit -keepAliveTime参数的时间单位
         * orkQueue -执行前用于保持任务的队列。此队列仅保持由execute方法提交的Runnable任务
         */
        ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(5,10,3,TimeUnit.MILLISECONDS,blockingQueue);

        Thread thread1=new ThreadExtend_Pool_Custom("Thread-1");
        Thread thread2=new ThreadExtend_Pool_Custom("Thread-2");
        Thread thread3=new ThreadExtend_Pool_Custom("Thread-3");
        Thread thread4=new ThreadExtend_Pool_Custom("Thread-4");
        Thread thread5=new ThreadExtend_Pool_Custom("Thread-5");

        //将线程放入线程池当中进行执行
        threadPoolExecutor.execute(thread1);
        threadPoolExecutor.execute(thread2);
        threadPoolExecutor.execute(thread3);

        //使用延迟执行的风格的方法
        threadPoolExecutor.execute(thread4);
        threadPoolExecutor.execute(thread5);

        //关闭线程池子
        threadPoolExecutor.shutdown();
    }
}

说明:
(1)、IllegalArgumentException-如果 corePoolSize或 keepAliveTime小于零,或者 maximumPoolSize小于或等于零,或者 corePoolSize大于maximumPoolSize。
(2)、NullPointerException-如果workQueue为 null
(3)、自定义连接池稍微麻烦些,不过通过创建的ThreadPoolExecutor线程池对象,可以获取到当前线程池的尺寸、正在执行任务的线程数、工作队列等等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值