Java实现自定义线程池

news2024/11/16 5:58:27

Java实现自定义线程池

image-20240910154502115

ThreadPool

public interface ThreadPool {

    void execute(Runnable runnable);

    void shutdown();

    int getInitSize();

    int getMaxSize();

    int getCoreSize();

    int getQueueSize();

    int getActiveCount();

    boolean isShutdown();
}

RunnableQueue

public interface RunnableQueue {

    void offer(Runnable runnable);

    Runnable take() throws InterruptedException;

    int size();
}

ThreadFactory

public interface ThreadFactory {

    Thread createThread(Runnable r);

}

DennyPolicy

public interface DennyPolicy {

    void reject(Runnable r, ThreadPool pool);

    class DiscardPolicy implements DennyPolicy {

        @Override
        public void reject(Runnable r, ThreadPool pool) {
            // do nothing
        }
    }

    class AbortPolicy implements DennyPolicy {

        @Override
        public void reject(Runnable r, ThreadPool pool) {
            throw new RejectedExecutionException();
        }
    }

    class RunnerDenyPolicy implements DennyPolicy {

        @Override
        public void reject(Runnable r, ThreadPool pool) {
            if (!pool.isShutdown()) {
                r.run();
            }
        }
    }

}

RunnableDenyException

public class RunnableDenyException extends RuntimeException {

    public RunnableDenyException(String message) {
        super(message);
    }

}

InternalTask

public class InternalTask implements Runnable{

    private final RunnableQueue runnableQueue;

    private volatile boolean running = true;

    public InternalTask(RunnableQueue runnableQueue) {
        this.runnableQueue = runnableQueue;
    }


    @Override
    public void run() {
        while (running && !Thread.currentThread().isInterrupted()) {
            try {
                Runnable task = runnableQueue.take();
                task.run();
            } catch (InterruptedException e) {
                running = false;
                break;
            }
        }
    }

    public void stop() {
        running = false;
    }

}

LinkedRunnableQueue

public class LinkedRunnableQueue implements RunnableQueue {

    private final int limit;

    private final DennyPolicy dennyPolicy;

    private final LinkedList<Runnable> runnableList = new LinkedList<>();

    private final ThreadPool threadPool;

    public LinkedRunnableQueue(final int limit, final DennyPolicy dennyPolicy, ThreadPool threadPool) {
        this.limit = limit;
        this.dennyPolicy = dennyPolicy;
        this.threadPool = threadPool;
    }

    @Override
    public void offer(Runnable runnable) {
        synchronized (runnableList) {
            if (runnableList.size() >= limit) {
                dennyPolicy.reject(runnable, threadPool);
            } else {
                runnableList.add(runnable);
                runnableList.notify();
            }
        }
    }

    @Override
    public Runnable take() throws InterruptedException {
        synchronized (runnableList) {
            while (runnableList.isEmpty()) {
                try {
                    runnableList.wait();
                } catch (InterruptedException e) {
                    throw e;
                }
            }
        }
        return runnableList.removeFirst();
    }

    @Override
    public int size() {
        synchronized (runnableList) {
            return runnableList.size();
        }
    }
}

BasicThreadPool

public class BasicThreadPool extends Thread implements ThreadPool {

    private final int initSize;
    private final int maxSize;
    private final int coreSize;
    private int activeCount;

    private final ThreadFactory threadFactory;

    private final RunnableQueue runnableQueue;

    private volatile boolean isShutdown = false;

    private final Queue<ThreadTask> threadQueue = new ArrayDeque<ThreadTask>();

    private final static DennyPolicy DEFAULT_DENNY_POLICY = new DennyPolicy.DiscardPolicy();

    private final static ThreadFactory DEFAULT_THREAD_FACTORY = new DefaultThreadFactory();

    private final long keepAliveTime;

    private final TimeUnit timeUnit;

    public BasicThreadPool(int initSize, int maxSize, int coreSize, int queueSize) {
        this(initSize, maxSize, coreSize, DEFAULT_THREAD_FACTORY, queueSize, DEFAULT_DENNY_POLICY, 10, TimeUnit.SECONDS);
    }

    public BasicThreadPool(int initSize, int maxSize, int coreSize, ThreadFactory threadFactory, int queueSize, DennyPolicy dennyPolicy, long keepAliveTime, TimeUnit unit) {
        this.initSize = initSize;
        this.maxSize = maxSize;
        this.coreSize = coreSize;
        this.threadFactory = threadFactory;
        this.runnableQueue = new LinkedRunnableQueue(queueSize, dennyPolicy, this);
        this.keepAliveTime = keepAliveTime;
        this.timeUnit = unit;
        this.init();
    }

    private void init() {
        start();
        for (int i = 0; i < initSize; i++) {
            newThread();
        }
    }

    private void newThread() {
        InternalTask internalTask = new InternalTask(runnableQueue);
        Thread thread = this.threadFactory.createThread(internalTask);
        ThreadTask threadTask = new ThreadTask(thread, internalTask);
        threadQueue.offer(threadTask);
        this.activeCount++;
        thread.start();
    }

    private void removeThread() {
        ThreadTask threadTask = threadQueue.remove();
        threadTask.internalTask.stop();
        this.activeCount--;
    }

    @Override
    public void run() {
        while (!isShutdown && !isInterrupted()) {
            try {
                timeUnit.sleep(keepAliveTime);
            } catch (InterruptedException e) {
                isShutdown = true;
                break;
            }

            synchronized (this) {
                if (isShutdown) {
                    break;
                }

                if (runnableQueue.size() > 0 && activeCount < coreSize) {
                    for (int i = initSize; i < coreSize; i++) {
                        newThread();
                    }
                    continue;
                }

                if (runnableQueue.size() > 0 && activeCount < maxSize) {
                    for (int i = coreSize; i < maxSize; i++) {
                        newThread();
                    }
                }

                if (runnableQueue.size() == 0 && activeCount > coreSize) {
                    for (int i = coreSize; i < activeCount; i++) {
                        removeThread();
                    }
                }

            }
        }
    }

    private static class ThreadTask {

        Thread thread;
        InternalTask internalTask;

        public ThreadTask(Thread thread, InternalTask internalTask) {
            this.thread = thread;
            this.internalTask = internalTask;
        }
    }

    @Override
    public void execute(Runnable runnable) {
        if (this.isShutdown) {
            throw new IllegalStateException("ThreadPool is closed");
        }
        this.runnableQueue.offer(runnable);
    }

    @Override
    public void shutdown() {
        synchronized (this) {
            if (isShutdown) {
                return;
            }

            isShutdown = true;
            threadQueue.forEach(threadTask -> {
                threadTask.internalTask.stop();
                threadTask.thread.interrupt();
            });
            this.interrupt();
        }
    }

    @Override
    public int getInitSize() {
        if (isShutdown) {
            throw new IllegalStateException("ThreadPool is closed");
        }
        return this.initSize;
    }

    @Override
    public int getMaxSize() {
        if (isShutdown) {
            throw new IllegalStateException("ThreadPool is closed");
        }
        return this.maxSize;
    }

    @Override
    public int getCoreSize() {
        if (isShutdown) {
            throw new IllegalStateException("ThreadPool is closed");
        }
        return this.coreSize;
    }

    @Override
    public int getQueueSize() {
        if (isShutdown) {
            throw new IllegalStateException("ThreadPool is closed");
        }
        return runnableQueue.size();
    }

    @Override
    public int getActiveCount() {
        synchronized (this) {
            return activeCount;
        }
    }

    @Override
    public boolean isShutdown() {
        return this.isShutdown;
    }

    private static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger GROUP_COUNTER = new AtomicInteger(1);

        private static final ThreadGroup group = new ThreadGroup("MyThreadPool" + GROUP_COUNTER.getAndDecrement());

        private static final AtomicInteger COUNTER = new AtomicInteger(1);

        @Override
        public Thread createThread(Runnable runnable) {
            return new Thread(group, runnable, "thread-pool-" + COUNTER.getAndDecrement());
        }
    }

}

ThreadPoolTest

public class ThreadPoolTest {

    public static void main(String[] args) throws InterruptedException {

        final BasicThreadPool threadPool = new BasicThreadPool(2, 6, 4, 1000);

        for (int i = 0; i < 20; i++) {
            threadPool.execute(() -> {
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        for (; ; ) {
            System.out.println("getActiveCount() = " + threadPool.getActiveCount());
            System.out.println("getQueueSize() = " + threadPool.getQueueSize());
            System.out.println("getCoreSize() = " + threadPool.getCoreSize());
            System.out.println("getMaxsize() = " + threadPool.getMaxSize());
            System.out.println("=============================================");
            TimeUnit.SECONDS.sleep(5);
        }
    }
}

运行结果

getActiveCount() = 2
getQueueSize() = 18
getCoreSize() = 4
getMaxsize() = 6
=============================================
getActiveCount() = 2
getQueueSize() = 18
getCoreSize() = 4
getMaxsize() = 6
=============================================
getActiveCount() = 4
getQueueSize() = 14
getCoreSize() = 4
getMaxsize() = 6
=============================================
getActiveCount() = 4
getQueueSize() = 14
getCoreSize() = 4
getMaxsize() = 6
=============================================
getActiveCount() = 6
getQueueSize() = 8
getCoreSize() = 4
getMaxsize() = 6
=============================================
getActiveCount() = 6
getQueueSize() = 8
getCoreSize() = 4
getMaxsize() = 6
=============================================
getActiveCount() = 6
getQueueSize() = 2
getCoreSize() = 4
getMaxsize() = 6
=============================================
getActiveCount() = 6
getQueueSize() = 2
getCoreSize() = 4
getMaxsize() = 6
=============================================
getActiveCount() = 5
getQueueSize() = 0
getCoreSize() = 4
getMaxsize() = 6
=============================================
getActiveCount() = 5
getQueueSize() = 0
getCoreSize() = 4
getMaxsize() = 6
=============================================
getActiveCount() = 4
getQueueSize() = 0
getCoreSize() = 4
getMaxsize() = 6
=============================================
getActiveCount() = 4
getQueueSize() = 0
getCoreSize() = 4
getMaxsize() = 6
=============================================

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2121615.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Windows10 Paddlepaddle-GPU CUDA CUDNN 版本选择

最终选择&#xff1a; 在创建的新环境下 python 3.8.* paddlepaddle-gpu 2.5.1.post120 CUDA 12.0 CUDNN 8.9&#xff08;需配合CUDA的版本&#xff09; 1. 本机GPU硬件信息 打开NVIDIA Control Panel->System Information->Components&#xff0c;…

深度解析:如何注册并培育亚马逊测评买家号?

在亚马逊这个全球热门的电商平台上&#xff0c;产品评价对于卖家而言至关重要&#xff0c;它直接影响着产品的曝光率、转化率以及消费者的购买意愿。因此&#xff0c;亚马逊测评账号的注册与养号成为了许多卖家关注的焦点。本文将介绍亚马逊测评账号的注册流程以及高效养号的一…

[数据集][目标检测]百事可乐可口可乐瓶子检测数据集VOC+YOLO格式195张2类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;195 标注数量(xml文件个数)&#xff1a;195 标注数量(txt文件个数)&#xff1a;195 标注类别…

RS485工业通信网关原理详解-天拓四方

一、引言 随着工业自动化技术的飞速发展&#xff0c;工业通信网关作为连接各种设备和系统的关键节点&#xff0c;发挥着越来越重要的作用。RS485工业通信网关作为其中的佼佼者&#xff0c;以其高可靠性、长距离传输能力和抗干扰能力强的特点&#xff0c;在工业自动化、楼宇自控…

经纬恒润高压电池管理系统,助力新能源汽车飞速发展

随着新能源汽车行业的快速发展&#xff0c;电池管理系统作为关键技术之一&#xff0c;其重要性日益凸显。经纬恒润自主研发的高压电池管理系统&#xff08;Battery Management System&#xff0c;BMS&#xff09;&#xff0c;凭借卓越的性能与先进的技术&#xff0c;在新能源汽…

【区块链通用服务平台及组件】微言科技数据智能中台

人工智能技术中的机器学习、深度学习依赖于海量数据进行模型训练&#xff0c;仅依靠某一机构的数据&#xff0c;无法实现模型、 算法的快速突破。然而数据要素流通涉及多方主体、多个环节&#xff0c;共享环境复杂&#xff0c;同时数据产品具有极易复制、非排他性、难追溯等特征…

为明天做好准备,摆脱传统财务规划的不足

对于企业规划和财务团队来说&#xff0c;自动化工具和创新技术虽说都能够有力支持企业实现数字化转型&#xff0c;进行符合时代发展的战略规划&#xff0c;但同时也伴随着一定的限制。回溯上个世界七十年代&#xff0c;电子表格的问世改变了经济世界的管理模式&#xff0c;带来…

数据智能驱动的工业互联网:能否真正解决企业成本问题?

数据智能驱动的工业互联网&#xff1a;能否真正解决企业成本问题&#xff1f; 前言数据智能驱动的工业互联网 前言 工业互联网作为推动制造业转型升级的关键力量&#xff0c;正逐渐展现出其巨大的潜力和影响力。随着信息技术的不断发展和应用&#xff0c;工业互联网的概念应运…

ctfshow-web入门-sql注入(web241、web242、web243)delete file 注入

目录 1、web241 2、web242 3、web243 1、web241 //删除记录$sql "delete from ctfshow_user where id {$id}"; 这里是 delete 语句&#xff0c;查询出来的东西不会有回显&#xff0c;因此采用盲注。如果采用布尔盲注&#xff0c;我们需要根据页面的回显情况来判…

电影《西施新传》首映礼,九月金秋全国正式公映

2024年9月1日&#xff0c;古装谋略情感影片《西施新传》在无锡大世界影城中山路IMAX激光店举办首映礼。电影《西施新传》根据作家沈雅琴、笔名一蝶的同名小说改编&#xff0c;以家喻户晓四大美人之首的西施为主人公&#xff0c;讲述了春秋末期吴越战争的故事。越国败于吴国&…

Spring Boot 注解探秘:常用配置值读取注解的魔力

在 Spring Boot 应用开发中&#xff0c;我们会常常借助Apollo&#xff0c;Spring Cloud Config等配置中心来集中管理配置信息&#xff0c;在拥有配置信息之后&#xff0c;高效且准确地读取这些配置信息无疑是极为关键的一环。今天我们就来介绍几个常用的用于配置值读取的注解。…

基于云函数的自习室预约微信小程序+LW示例参考

全阶段全种类学习资源&#xff0c;内涵少儿、小学、初中、高中、大学、专升本、考研、四六级、建造师、法考、网赚技巧、毕业设计等&#xff0c;持续更新~ 文章目录 [TOC](文章目录) 1.项目介绍2.项目部署3.项目部分截图4.获取方式 1.项目介绍 技术栈工具&#xff1a;云数据库…

联想 ThinkSystem DM3000H 混合闪存阵列,助力浙江石油化工全面优化私有云数据管理平台

国内石油化工行业领军企业浙江石油化工有限公司&#xff08;以下简称“浙石化”&#xff09;成立于 2015 年&#xff0c;是一家民企控股、国企参股的混合所有制企业。由浙石化投资建设的炼化一体化项目是国内最大的一次性绿地投资建设的炼化一体化项目&#xff0c;项目规划总面…

十二、新版UI

一、UI Toolkit 这个组件是新版的UI系统 创建了一个新的UIBuild&#xff0c;在单独的场景中打开 未来Unity会以这个为基准。 缺点&#xff1a;目前没有Animator&#xff0c;做不了动画&#xff1b;没法加shader

前端用html写excel文件直接打开

源码 <html xmlns:o"urn:schemas-microsoft-com:office:office" xmlns:x"urn:schemas-microsoft-com:office:excel" xmlns"http://www.w3.org/TR/REC-html40"> <head><meta charset"UTF-8"><!--[if gte mso 9]&…

智能风扇的全新升级:NRK3603语音芯片识别控制模块的应用

在当今智能化生活的潮流中&#xff0c;如何让家电更加人性化、便捷化&#xff0c;已经成为消费者和制造商关注的焦点。在这股大潮中&#xff0c;NRK3603语音识别模块以其出色的性能和广泛的应用&#xff0c;为智能电风扇带来了全新的升级。 1. 芯片特性 NRK3603是一款高性能、…

ADTEC自动阻抗匹配器维修AMVG-2000-FY AMVG-1000-CD

提供全系列ADTEC自动阻抗匹配器维修&#xff0c;射频电源维修。 ADTEC自动阻抗匹配网络可以实现高速自动整合&#xff0c;该系列设备装备了可以通过个人电脑操作和测量的AMV软件&#xff0c;设备内置了用于预设和LC网络的标准库&#xff0c;还可以根据客户要求进行定制&#x…

高颜值官网(1):百货类网站UI,拓展一下你的眼界。

Hi、我是大千UI工场&#xff0c;本期开始每次分享8-10个各行业的大气颜值官网&#xff0c;欢迎关注我&#xff0c;以便及时收到更新消息&#xff0c;我是10年UI和前端领域老司机了&#xff0c;一定不负所望。

代码随想录 - 1 - 数组 - 二分查找

代码随想录&#xff1a;代码随想录 一.数组理论基础 数组是存放在连续内存空间上的相同类型数据的集合 数组可以方便的通过下标索引的方式获取到下标对应的数据 需要注意&#xff1a; 数组下标都是从0开始的数组内存空间的地址是连续的正是因为数组在内存空间的地址是连续的&…

post请求中有[]报400异常

序言 在和前端同学联调的时候&#xff0c;发现只要post请求参数里面有[]&#xff0c;就会报400的错误 可以看到日志中&#xff1a; The valid characters are defined in RFC 7230 and RFC 3986 解决办法&#xff1a; 参考了博客&#xff1a; spring boot 中解决post请求中有…