当前位置: 代码网 > it编程>编程语言>Java > Spring线程池的配置及使用ThreadPoolTaskExecutor过程

Spring线程池的配置及使用ThreadPoolTaskExecutor过程

2026年03月30日 Java 我要评论
一、threadpooltaskexecutor是什么?threadpooltaskexecutor是spring提供的线程池,通过配置参数初始化线程池,随取随用,不需要操作线程的创建和销毁。二、代码

一、threadpooltaskexecutor是什么?

threadpooltaskexecutor是spring提供的线程池,通过配置参数初始化线程池,随取随用,不需要操作线程的创建和销毁。

二、代码实现

1.配置类executorconfig

代码如下(示例):

@configuration
@enableasync
public class executorconfig {

    private static final logger logger = loggerfactory.getlogger(executorconfig.class);

    private int corepoolsize = 5;
    private int maxpoolsize = 10;
    private int queuecapacity = 99999;
    private string nameprefix = "async-service-";

    @bean(name = "asyncserviceexecutor")
    public threadpooltaskexecutor asyncserviceexecutor(){
        logger.info("start asyncserviceexecutor");
        threadpooltaskexecutor executor = new threadpooltaskexecutor();
        //配置核心线程数
        executor.setcorepoolsize(corepoolsize);
        //配置最大线程数
        executor.setmaxpoolsize(maxpoolsize);
        //配置队列大小
        executor.setqueuecapacity(queuecapacity);
        //配置线程池中的线程的名称前缀
        executor.setthreadnameprefix(nameprefix);

        // rejection-policy: 当pool已经达到max size的时候,如何处理新任务
        // caller_runs: 不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setrejectedexecutionhandler(new threadpoolexecutor.callerrunspolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}

2.引入使用

代码如下(示例):

    @resource(name = "asyncserviceexecutor")
    private threadpooltaskexecutor executor;

	//定义计数器
	final countdownlatch countdownlatch=new countdownlatch(list.size());
	executor.execute(()-> {
                    try {
						//do something
                    } catch (exception e) {
                        log.error(e.getmessage());
                    } finally {
                        log.info(thread.currentthread().getname() + "执行完成");
                        //计数器减一
                        countdownlatch.countdown();
                    }
                });

            try {
                countdownlatch.await();
                executor.shutdownnow();
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
            //do something

三、fixedthreadpool线程池

我们在开发中经常会用到java提供的工具类创建线程池,fixedthreadpool就是其中之一,但在使用中要注意这个线程池一旦开启会引起内存飙升的问题,下面我们来看下源码。

executorservice fixedthreadpool = executors.newfixedthreadpool(5);
//定义计数器
	final countdownlatch countdownlatch=new countdownlatch(list.size());
	fixedthreadpool.execute(()-> {
                    try {
						//do something
                    } catch (exception e) {
                        log.error(e.getmessage());
                    } finally {
                        log.info(thread.currentthread().getname() + "执行完成");
                        //计数器减一
                        countdownlatch.countdown();
                    }
                });

            try {
                countdownlatch.await();
                fixedthreadpool.shutdownnow();
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
            //do something


上面两图是截图出来的源码,重点就在这个new出来的队列,通常称为无界队列,因为这个队列默认大小是interger.max_value,所以在线程池创建的一瞬间内存就会飙升,直到所有线程执行完毕,关闭线程池,才会释放内存

总结

注意:

  • 计数器的定义是为了保证:线程池全部执行完for循环中的内容,再执行后续的内容。
  • 如果不需要保证执行顺序,可以不使用计数器。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com