java入门-自定义线程池

阿里在规范中明确规定不使用jdk中的线程池,原因是jdk中线程池没有对队列大小规范,可能会造成java虚拟机内存异常。
image-20231204164947358
image-20231204165055465

在面试中中小公司也喜欢对自定义线程进行考核。我们尝试以简单的方式来讲解如何自定义线程池。

JDK常用线程池

以下列举出了JDK实现的线程池,虽然在项目中禁止使用,但是可以给我们提供良好的自定义线程实现案例。
Executors

  • newSingleThreadExecutor
  • newFixedThreadExecutor
  • newCachedThreadPool
  • newScheduledThreadPool

自定义线程

自定义线程池模型
image-20230907095431190
线程池常用七大参数
序列参数名含义
1corePoolSize核心线程数
2maximumPoolSize最大线程数(必须大于核心线程数)
3keepAliveTime空闲线程的存活时间
4Unit时间单位
5workQueue用于存放任务的队列
6threadFactory线程工厂、用来创建新线程
7handler处理别拒绝的任务
自定义线程池实现
 int corePoolSize = 4;
        int maximumPoolSize = 10;
        long keepAliveTime= 10000;
        TimeUnit unit = TimeUnit.MILLISECONDS;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(10);
        ThreadFactory threadFactory=null;
        RejectedExecutionHandler handler=null;

        ThreadPoolExecutor myPool = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
package com.wnhz.thread;

import java.util.concurrent.*;

public class CustomerThreadPool {

 /**
  * 定义线程池工厂,目的产生线程
  */
  static  class SimpleThreadFactory implements ThreadFactory {
        public Thread newThread(Runnable r) {
            return new Thread(r);
        }
    }
/**
 * 定义拒绝策略
 */
    static class MyAbortPolicy implements RejectedExecutionHandler {
        /**
         * Creates an {@code AbortPolicy}.
         */
        public MyAbortPolicy() { }

        /**
         * 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("任务 " + r.toString() +
                    " 拒绝 from " +
                    e.toString());
        }
    }

    public static void main(String[] args) {
        int corePoolSize = 4;
        int maximumPoolSize = 10;
        long keepAliveTime = 10000;
        TimeUnit unit = TimeUnit.MILLISECONDS;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(10);
//        ThreadFactory threadFactory = new ThreadFactory() {
//            @Override
//            public Thread newThread(Runnable r) {
//                System.out.println("创建线程:"+r);
//                return new Thread(r);
//            }
//        };
        RejectedExecutionHandler handler = null;

        ThreadPoolExecutor myPool = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                r->{
                    System.out.println("创建线程:"+r);
                    return new Thread(r);
                },
                new MyAbortPolicy()
        );

        for (int t=0;t<20;t++) {
            myPool.execute(()->{
                for (int i=0;i<10;i++) {
                    System.out.println(Thread.currentThread().getName()+":"+i);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值