`

线程池实例:使用Executors和ThreadPoolExecutor

阅读更多

        线程池负责管理工作线程,包含一个等待执行的任务队列。线程池的任务队列是一个Runnable集合,工作线程负责从任务队列中取出并执行Runnable对象。

        java.util.concurrent.executors 提供了 java.util.concurrent.executor 接口的一个Java实现,可以创建线程池。下面是一个简单示例:

        首先创建一个Runable 类:

WorkerThread.java

package com.bijian.study;

public class WorkerThread implements Runnable {
	 
    private String command;
 
    public WorkerThread(String s){
        this.command=s;
    }
 
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
        processCommand();
        System.out.println(Thread.currentThread().getName()+" End.");
    }
 
    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public String toString(){
        return this.command;
    }
}

        下面是一个测试程序,从 Executors 框架中创建固定大小的线程池:

SimpleThreadPool.java

package com.bijian.study;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class SimpleThreadPool {
 
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
          }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}

        在上面的程序中,我们创建了包含5个工作线程的固定大小线程池。然后,我们向线程池提交10个任务。由于线程池的大小是5,因此首先会启动5个工作线程,其他任务将进行等待。一旦有任务结束,工作线程会从等待队列中挑选下一个任务并开始执行。

        以上程序的输出结果如下:

pool-1-thread-1 Start. Command = 0
pool-1-thread-4 Start. Command = 3
pool-1-thread-5 Start. Command = 4
pool-1-thread-2 Start. Command = 1
pool-1-thread-3 Start. Command = 2
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-1 End.
pool-1-thread-5 End.
pool-1-thread-3 End.
pool-1-thread-5 Start. Command = 8
pool-1-thread-1 Start. Command = 7
pool-1-thread-2 Start. Command = 5
pool-1-thread-4 Start. Command = 6
pool-1-thread-3 Start. Command = 9
pool-1-thread-3 End.
pool-1-thread-2 End.
pool-1-thread-1 End.
pool-1-thread-4 End.
pool-1-thread-5 End.
Finished all threads

        从输出结果看,线程池中有五个名为“pool-1-thread-1”…“pool-1-thread-5”的工作线程负责执行提交的任务。

        Executors 类使用 ExecutorService  提供了一个 ThreadPoolExecutor 的简单实现,但ThreadPoolExecutor 提供的功能远不止这些。我们可以指定创建 ThreadPoolExecutor 实例时活跃的线程数,并且可以限制线程池的大小,还可以创建自己的 RejectedExecutionHandler 实现来处理不适合放在工作队列里的任务。

        下面是一个 RejectedExecutionHandler 接口的自定义实现:

RejectedExecutionHandlerImpl.java

package com.bijian.study;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
 
public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {
 
    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        System.out.println(r.toString() + " is rejected");
    }
}

        ThreadPoolExecutor 提供了一些方法,可以查看执行状态、线程池大小、活动线程数和任务数。所以,我通过一个监视线程在固定间隔输出执行信息。

MyMonitorThread.java

package com.bijian.study;

import java.util.concurrent.ThreadPoolExecutor;

public class MyMonitorThread implements Runnable
{
    private ThreadPoolExecutor executor;
 
    private int seconds;
 
    private boolean run=true;
 
    public MyMonitorThread(ThreadPoolExecutor executor, int delay)
    {
        this.executor = executor;
        this.seconds=delay;
    }
 
    public void shutdown(){
        this.run=false;
    }
 
    @Override
    public void run()
    {
        while(run){
                System.out.println(
                    String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s",
                        this.executor.getPoolSize(),
                        this.executor.getCorePoolSize(),
                        this.executor.getActiveCount(),
                        this.executor.getCompletedTaskCount(),
                        this.executor.getTaskCount(),
                        this.executor.isShutdown(),
                        this.executor.isTerminated()));
                try {
                    Thread.sleep(seconds*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
 
    }
}

        下面是使用 ThreadPoolExecutor 的线程池实现示例:

WorkerPool.java

package com.bijian.study;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
 
public class WorkerPool {
 
    public static void main(String args[]) throws InterruptedException {
    	
        //RejectedExecutionHandler implementation
        RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();
        //Get the ThreadFactory implementation to use
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        //creating the ThreadPoolExecutor
        ThreadPoolExecutor executorPool = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), threadFactory, rejectionHandler);
        //start the monitoring thread
        MyMonitorThread monitor = new MyMonitorThread(executorPool, 3);
        Thread monitorThread = new Thread(monitor);
        monitorThread.start();
        //submit work to the thread pool
        for(int i=0; i<10; i++){
            executorPool.execute(new WorkerThread("cmd"+i));
        }
 
        Thread.sleep(30000);
        //shut down the pool
        executorPool.shutdown();
        //shut down the monitor thread
        Thread.sleep(5000);
        monitor.shutdown();
    }
}

        请注意:在初始化 ThreadPoolExecutor 时,初始线程池大小设为2、最大值设为4、工作队列大小设为2。所以,如果当前有4个任务正在运行,而此时又有新任务提交,工作队列将只存储2个任务,其他任务将交由RejectedExecutionHandlerImpl 处理。

        程序执行的结果如下,确认了上面的结论:

pool-1-thread-2 Start. Command = cmd1
cmd6 is rejected
cmd7 is rejected
cmd8 is rejected
cmd9 is rejected
pool-1-thread-4 Start. Command = cmd5
pool-1-thread-1 Start. Command = cmd0
pool-1-thread-3 Start. Command = cmd4
[monitor] [0/2] Active: 0, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 4, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-1 End.
pool-1-thread-3 End.
pool-1-thread-4 Start. Command = cmd3
pool-1-thread-2 Start. Command = cmd2
[monitor] [4/2] Active: 2, Completed: 4, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 2, Completed: 4, Task: 6, isShutdown: false, isTerminated: false
pool-1-thread-2 End.
pool-1-thread-4 End.
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true

        请注意活跃线程、已完成线程和任务完成总数的变化。我们可以调用 shutdown() 结束所有已提交任务并终止线程池。

        再修改WorkerPool.java,将工作队列大小设为3,如下所示:

//creating the ThreadPoolExecutor
ThreadPoolExecutor executorPool = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3), threadFactory, rejectionHandler);

        运行结果如下:

pool-1-thread-1 Start. Command = cmd0
pool-1-thread-2 Start. Command = cmd1
pool-1-thread-4 Start. Command = cmd6
cmd7 is rejected
pool-1-thread-3 Start. Command = cmd5
cmd8 is rejected
cmd9 is rejected
[monitor] [0/2] Active: 0, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 4, Completed: 0, Task: 7, isShutdown: false, isTerminated: false
pool-1-thread-3 End.
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-1 End.
pool-1-thread-4 Start. Command = cmd4
pool-1-thread-2 Start. Command = cmd3
pool-1-thread-3 Start. Command = cmd2
[monitor] [4/2] Active: 3, Completed: 4, Task: 7, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 3, Completed: 4, Task: 7, isShutdown: false, isTerminated: false
pool-1-thread-2 End.
pool-1-thread-3 End.
pool-1-thread-4 End.
[monitor] [4/2] Active: 0, Completed: 7, Task: 7, isShutdown: false, isTerminated: false
[monitor] [3/2] Active: 0, Completed: 7, Task: 7, isShutdown: false, isTerminated: false
[monitor] [3/2] Active: 0, Completed: 7, Task: 7, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 7, Task: 7, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 7, Task: 7, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 7, Task: 7, isShutdown: false, isTerminated: false
[monitor] [0/2] Active: 0, Completed: 7, Task: 7, isShutdown: true, isTerminated: true
[monitor] [0/2] Active: 0, Completed: 7, Task: 7, isShutdown: true, isTerminated: true

        在初始化 ThreadPoolExecutor 时,初始线程池大小设为2、最大值设为4、工作队列大小设为3。所以,如果当前有4个任务正在运行,而此时又有新任务提交,工作队列将只存储3个任务,其他任务将交由RejectedExecutionHandlerImpl 处理。

        进一步查看ThreadPoolExecutor的此构造方法源代码如下:

/**
 * Creates a new {@code ThreadPoolExecutor} with the given initial
 * parameters.
 *
 * @param corePoolSize the number of threads to keep in the pool, even
 *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
 * @param maximumPoolSize the maximum number of threads to allow in the
 *        pool
 * @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.
 * @param unit the time unit for the {@code keepAliveTime} argument
 * @param workQueue the queue to use for holding tasks before they are
 *        executed.  This queue will hold only the {@code Runnable}
 *        tasks submitted by the {@code execute} method.
 * @param threadFactory the factory to use when the executor
 *        creates a new thread
 * @param handler the handler to use when execution is blocked
 *        because the thread bounds and queue capacities are reached
 * @throws IllegalArgumentException if one of the following holds:<br>
 *         {@code corePoolSize < 0}<br>
 *         {@code keepAliveTime < 0}<br>
 *         {@code maximumPoolSize <= 0}<br>
 *         {@code maximumPoolSize < corePoolSize}
 * @throws NullPointerException if {@code workQueue}
 *         or {@code threadFactory} or {@code handler} is null
 */
public ThreadPoolExecutor(int corePoolSize,
						  int maximumPoolSize,
						  long keepAliveTime,
						  TimeUnit unit,
						  BlockingQueue<Runnable> workQueue,
						  ThreadFactory threadFactory,
						  RejectedExecutionHandler handler) {
	if (corePoolSize < 0 ||
		maximumPoolSize <= 0 ||
		maximumPoolSize < corePoolSize ||
		keepAliveTime < 0)
		throw new IllegalArgumentException();
	if (workQueue == null || threadFactory == null || handler == null)
		throw new NullPointerException();
	this.corePoolSize = corePoolSize;
	this.maximumPoolSize = maximumPoolSize;
	this.workQueue = workQueue;
	this.keepAliveTime = unit.toNanos(keepAliveTime);
	this.threadFactory = threadFactory;
	this.handler = handler;
}

        如果希望延迟执行或定期运行任务,那么可以使用 ScheduledThreadPoolExecutor 类。要了解更多,请参见 Java Schedule Thread Pool Executor

 

文章来源:http://www.importnew.com/8542.html

分享到:
评论

相关推荐

    AIGC-基于ControlNet的AI视频生成算法-支持动漫+写实风格转换-附项目源码+流程教程-优质项目实战

    AIGC_基于ControlNet的AI视频生成算法_支持动漫+写实风格转换_附项目源码+流程教程_优质项目实战

    wjf0214_qd-templates_1742851862.zip

    app开发

    毕业设计指南-word

    毕业设计指南-word

    《基于YOLOv8的无人便利店监控系统》(包含源码、完整数据集、可视化界面、部署教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计.zip

    资源内项目源码是来自个人的毕业设计,代码都测试ok,包含源码、数据集、可视化页面和部署说明,可产生核心指标曲线图、混淆矩阵、F1分数曲线、精确率-召回率曲线、验证集预测结果、标签分布图。都是运行成功后才上传资源,毕设答辩评审绝对信服的保底85分以上,放心下载使用,拿来就能用。包含源码、数据集、可视化页面和部署说明一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.txt文件,仅供学习参考, 切勿用于商业用途。

    渗透测试之信息收集思维导图

    信息收集思维导图

    三维偏微分方程组的数值解法与一阶近似推导-基于有限差分法的Python实现(复现论文或解决问题,含详细可运行代码及解释)

    内容概要:本文详细介绍了三维偏微分方程组的数值解法及其一阶近似的推导过程。首先,针对定义在一个三维立方体域上的六个耦合偏微分方程组,选择了有限差分法(FDM)作为数值求解的方法。文中提供了详细的离散化步骤、边界条件设定以及迭代求解的具体实现,并附带了完整的Python代码用于求解和可视化结果。其次,通过对六个方程的线性组合,推导出了一阶近似方程,证明了在特定条件下,系统的演化可以由一个扩散方程来描述。最后,对不同参数σ下的数值结果进行了分析,展示了不同σ值对解的影响。 适合人群:具备数学建模和编程基础的研究人员和技术爱好者,尤其是对偏微分方程数值解感兴趣的学者。 使用场景及目标:适用于需要解决复杂物理现象模拟的问题,如流体力学、热传导等领域。通过学习本文,读者能够掌握有限差分法的基本思想和应用技巧,同时理解如何利用Python进行科学计算和数据可视化。 其他说明:本文不仅提供理论推导,还给出了具体的代码实现,便于读者理解和复现实验结果。此外,文中涉及的可视化部分可以帮助直观地展示数值解的特点和变化趋势。

    大数据项目深度研究分析报告.docx

    大数据项目深度研究分析报告.docx

    连接打印机0x0000709错误修复方法

    对于WIN11系统连接共享打印机出现提示:windows无法连接到打印机,请检查 打印机名并重试,以及“操作无法完成(错误 0x00000709)”等提示进行解决。

    Docker入门与实战指南:镜像与容器的全流程解析

    内容概要:本文详细介绍了Docker的重要概念、常用指令及其应用场景,旨在帮助初学者快速掌握Docker的使用方法。主要内容涵盖镜像和容器的概念区分、镜像的获取方式(网络拉取、本地加载)、镜像的使用(查看、创建容器、删除)、容器的管理(进入、退出、停止、删除)、镜像的生成(自动构建、手动提交)以及镜像的分享(在线存储库、本地导出)。此外,还涉及了无用数据的清理和一些常用的可视化管理工具。 适合人群:对Docker感兴趣的初学者,尤其是希望快速上手并应用于实际项目的开发人员。 使用场景及目标:适用于需要快速搭建一致运行环境、进行应用部署和维护的技术团队。通过学习本文,读者能够独立完成Docker环境的搭建、镜像和容器的管理,从而提高开发效率和环境一致性。 其他说明:文中提供了丰富的实例和官方文档链接,便于读者深入理解和实践。同时,附带了一些实用的参考资料,方便进一步探索Docker的高级特性。

    鞍山市乡镇边界,矢量边界,shp格式

    矢量边界,行政区域边界,精确到乡镇街道,可直接导入arcgis使用

    动态综合评价中的无量纲化方法及其Python实现(复现论文,含详细可运行代码及解释)

    内容概要:本文详细介绍了动态综合评价中的无量纲化方法,并提供了Python代码实现。主要内容包括:数据准备、静态无量纲化方法(极差法、Z-score标准化、均值法)、三种动态无量纲化改进方法(标准序列法、全序列法、增量权法)。文中还进行了结果分析与比较,得出了全序列法是最推荐的方法,因其能够同时保留横向和纵向信息。最后,文章展示了如何将这些方法应用于TOPSIS综合评价系统,以及如何通过熵权法计算权重。 适合人群:具备一定数据分析和编程基础的研究人员、数据科学家、工程师。 使用场景及目标:适用于需要对多维时序数据进行无量纲化处理和综合评价的场景,如生产质量监控、供应商评估等。目标是帮助用户理解和实现动态综合评价中的无量纲化方法,提高数据处理和分析能力。 其他说明:本文不仅提供了详细的代码实现,还通过实例验证了不同方法的效果,确保读者能够深入理解每种方法的特点和应用场景。

    腾讯AI封装调用,针对腾讯的AI产品进行封装调用

    腾讯AI封装调用

    《基于YOLOv8的零售商品识别系统》(包含源码、完整数据集、可视化界面、部署教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计.zip

    资源内项目源码是来自个人的毕业设计,代码都测试ok,包含源码、数据集、可视化页面和部署说明,可产生核心指标曲线图、混淆矩阵、F1分数曲线、精确率-召回率曲线、验证集预测结果、标签分布图。都是运行成功后才上传资源,毕设答辩评审绝对信服的保底85分以上,放心下载使用,拿来就能用。包含源码、数据集、可视化页面和部署说明一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.txt文件,仅供学习参考, 切勿用于商业用途。

    路径规划领域中A*算法的优化与改进及其应用场景

    内容概要:本文详细介绍了A*算法的传统框架及其在路径规划中的局限性,并提出了多项改进措施。首先,针对启发函数进行了优化,引入了基于机器学习的预测方法以及动态权重调整,使得路径更加智能化和平滑化。其次,在邻接表和优先队列方面采用了更高效的数据结构,提高了算法的执行效率。实验结果显示,改进后的A*算法不仅缩短了路径长度,还显著降低了运行时间和空间开销。此外,作者对比了多种常见路径规划算法(如Dijkstra、RRT),展示了改进A*算法在不同场景下的优越性能。 适合人群:从事机器人导航、自动驾驶、游戏开发等领域研究的技术人员,尤其是对路径规划算法有一定了解并希望深入探索优化方法的研究者。 使用场景及目标:①需要在二维或三维环境中进行高效路径规划的应用场合;②希望通过优化现有算法来提升系统性能的研发团队;③希望掌握更多关于路径规划理论和技术细节的学习者。 其他说明:文中提供了具体的MATLAB代码片段用于解释各个部分的具体实现方式,并分享了一些实用技巧,如优先队列的容器映射实现和动画绘制优化等。

    食品菜单_侧滑功能_列表展示_通用APP开发框架_1742855562.zip

    app开发

    word-【软考-网络工程师】学习资源

    网络工程师(中级)是软考(计算机技术与软件专业技术资格考试)的一部分,主要考察计算机网络基础、网络安全、网络管理、操作系统、数据库等内容,考试分为上午的基础知识选择题和下午的案例分析题。

    IoT最新进展111222

    IoT最新进展

    《基于YOLOv8的顾客行为分析系统》(包含源码、完整数据集、可视化界面、部署教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计.zip

    资源内项目源码是来自个人的毕业设计,代码都测试ok,包含源码、数据集、可视化页面和部署说明,可产生核心指标曲线图、混淆矩阵、F1分数曲线、精确率-召回率曲线、验证集预测结果、标签分布图。都是运行成功后才上传资源,毕设答辩评审绝对信服的保底85分以上,放心下载使用,拿来就能用。包含源码、数据集、可视化页面和部署说明一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.txt文件,仅供学习参考, 切勿用于商业用途。

    前端开发_VueCli3_H5模板_集成高德地图MintUI_1742856847.zip

    前端开发_VueCli3_H5模板_集成高德地图MintUI_1742856847.zip

Global site tag (gtag.js) - Google Analytics