首页 > 其他分享 >SPRING ThreadPoolTaskExecutor示例

SPRING ThreadPoolTaskExecutor示例

时间:2023-04-12 14:45:02浏览次数:48  
标签:示例 SPRING springframework com org import ThreadPoolTaskExecutor public

0、前言

当我们需要实现并发、异步等操作时,通常都会使用到ThreadPoolTaskExecutor。它是springcore包中的,而ThreadPoolExecutor是JDK中的JUC。ThreadPoolTaskExecutor是对ThreadPoolExecutor进行了封装处理。

1、示例

1.1、配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@EnableAsync
@Configuration
public class ExecutorConfig {

    @Bean(name = "asyncServiceExecutor")
    public Executor asyncServiceExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(10);
        //设置最大线程数
        executor.setMaxPoolSize(30);
        //设置队列大小
        executor.setQueueCapacity(50);
        //配置线程池的前缀
        executor.setThreadNamePrefix("async-service-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //设置空闲时间
        executor.setKeepAliveSeconds(60);
        //进行加载
        executor.initialize();
        return executor;
    }
}

1.2、应用

1.2.0 需异步的方法

import com.baomidou.mybatisplus.extension.service.IService;
import com.chengd.pojo.GeneCase;

public interface GeneCaseService extends IService<GeneCase>
{

    void testThread();
}
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chengd.mapper.GeneCaseMapper;
import com.chengd.pojo.GeneCase;
import com.chengd.service.GeneCaseService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class GeneCaseServiceImpl extends ServiceImpl<GeneCaseMapper, GeneCase> implements GeneCaseService {

    @Override
    @Async
    public void testThread() {
        for (int i = 0; i < 200; i++) {
            System.out.println("副线程名称 " + Thread.currentThread().getName() + " === " + i);
        }
    }
    
}

1.2.1 Controller

import com.chengd.common.Result;
import com.chengd.service.TestService;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/test")
@Api(tags = "测试ThreadPoolTaskExecutor")
public class TestController {

    @Resource
    private TestService testService;

    @GetMapping("/thread")
    public Result<Object> testThread() throws InterruptedException {
        testService.testThread();
        return Result.succeed("请求成功");
    }
}

1.2.2 Service

public interface TestService {

    /**
     * 测试Thread
     */
    void testThread() throws InterruptedException;

}
import com.chengd.service.GeneCaseService;
import com.chengd.service.TestService;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class TestServiceImpl implements TestService {

    @Resource
    private GeneCaseService geneCaseService;

    @Resource(name = "asyncServiceExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public void testThread() throws InterruptedException {

        threadPoolTaskExecutor.submit(() -> geneCaseService.testThread());

        threadPoolTaskExecutor.submit(() -> geneCaseService.testThread());

        for (int i = 0; i < 200; i++) {
            System.out.println("主线程名称 " + Thread.currentThread().getName() + " === " + i);
            Thread.sleep(10);
        }

    }
}

1.3、测试结果

注意事项:
配置类的 @EnableAsync
需异步方法的 @Async

标签:示例,SPRING,springframework,com,org,import,ThreadPoolTaskExecutor,public
From: https://www.cnblogs.com/jspider/p/17309744.html

相关文章

  • 22-springcloud-feign-4-使用Feign实现消费者的测试
    负载均衡:我们知道,SpringCloud提供了Ribbon来实现负载均衡,使用Ribbo直接注入一个RestTemplate对象即可,RestTemplate已经做好了负载均衡的配置;在SpringCloud下,使用Feign也是直接可以实现负载均衡的,定义一个有@FeignClient注解的接口,然后使用@RequestMapping注解......
  • SpringMVC 长轮询
    修改web.xml让其支持异步请求<filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param>&l......
  • 善借ChatGPT提效,Cursor四问答设计业务简一概念模型示例
    作为一个程序员,对新事物不好奇,没有学习新技术的自觉意识,不知道如何更好地运用工具来提升自己的效率,又如何保持自己的竞争力呢上一次文字创作:梦,仰望星空;路,脚踏实地今天看看辅助编程~上一篇工具Cursor介绍:人人都是程序员,AI神器Cursor辅助,体验自然语言编程第一问:请使用java帮我......
  • Springboot集成dubbo完整过程(三)
    准备工作1,准备mysql服务环境2,准备redis服务环境3,准备zookeeper服务环境4,准备逆向生成bean的xml配置文件5,准备slf4j日志xml配置文件6,准备一个sql脚本1,搭建创建服务工程1,创建一个空的父工程,用来统一管理依赖2,创建一个interface接口工程,主要存放业务bean,接口类3,创建一......
  • 17-springcloud-ribbon-3-Ribbon 负载均衡策略
    Ribbon的负载均衡策略是由IRule接口定义,该接口由如下实现:在jar包:com.netflix.ribbon#ribbon-loadbalancer中;  要使用ribbon实现负载均衡,在Spring的配置类里面把对应的负载均衡接口实现类作为一个Bean配置一下就行了;负载均衡的入口:ILoadBalancer接口如果要切换负载......
  • 16-springcloud-ribbon-2-ribbon实现服务调用
    1、首先加入ribbon的依赖,但是eureka已经依赖了ribbon,所以这里不需要再引用ribbon的依赖;2、要使用ribbon,只需要一个注解: @Bean@LoadBalancedpublic RestTemplaterestTemplate(){    RestTemplaterestTemplate=new RestTemplate();    return restTemplate;}在R......
  • springboot -eclipse安装springboot插件注意事项
    1.下载包,本地安装,在线安装容易出问题;2.下载的包版本要和eclipse版本一致;3.mac电脑显示和隐藏文件的方法:shift+command+<或者>,分别是显示和隐藏;4.大概率碰到编译报错说找不到org.eclipse.debug.core的问题,第三条就是为了显示隐藏文件,删除/.metadata/.plugins目录下的org.eclipse.......
  • Spring中Bean的实例化详细流程
    还是举个例子,我有一个朋友小汪他远赴南方某城市打工。然后安定下来后他的朋友很想来家里玩,但是呢我这个朋友家里搞的很乱,所以他不好意思请朋友来家里玩。这时我的另一个朋友说那请一个保姆把家里好好整理一下就可以了,然后给他介绍了一个保姆大S(PS:本文无意指向任何人,因为Spring的......
  • 动力节点王鹤SpringBoot3笔记——第七章 视图技术Thymeleaf
    7视图技术ThymeleafThymeleaf是一个表现层的模板引擎,一般被使用在Web环境中,它可以处理HTML,XML、JS等文档,简单来说,它可以将JSP作为JavaWeb应用的表现层,有能力展示与处理数据。Thymeleaf可以让表现层的界面节点与程序逻辑被共享,这样的设计,可以让界面设计人员、业......
  • 动力节点SpringBoot3笔记——视图技术Thymeleaf
    7视图技术ThymeleafThymeleaf是一个表现层的模板引擎,一般被使用在Web环境中,它可以处理HTML,XML、JS等文档,简单来说,它可以将JSP作为JavaWeb应用的表现层,有能力展示与处理数据。Thymeleaf可以让表现层的界面节点与程序逻辑被共享,这样的设计,可以让界面设计人员、业......