Java 线程池ThreadPoolTaskExecutor的使用demo

 

线程池大白话概括: 减少开销、方便管理

1. 定义配置

2. 定义接口

3. 实现接口

4. 控制测试

定义配置 ThreadConfig.java
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

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

@Configuration
@EnableAsync  // 启用异步任务
public class ThreadConfig implements AsyncConfigurer {

    /**
     * 获取当前cpu核数
     */
    public static final int corePoolSize = Runtime.getRuntime().availableProcessors();

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数:线程池创建时候初始化的线程数
        taskExecutor.setCorePoolSize(corePoolSize);
        // 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        taskExecutor.setMaxPoolSize(corePoolSize*2);
        // 缓冲队列:用来缓冲执行任务的队列
        taskExecutor.setQueueCapacity(500);
        //允许线程的空闲时间60秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁
        taskExecutor.setKeepAliveSeconds(60);

        //线程池对拒绝任务的处理策略:这里采用了CallerRunsPolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;
        //如果执行程序已关闭,则会丢弃该任务
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);

        //线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
        taskExecutor.setThreadNamePrefix("PGQ-taskexecutor-");

        //执行初始化
        taskExecutor.initialize();
        taskExecutor.afterPropertiesSet();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

定义接口 ITestThreadService.java
public interface ITestThreadService {


    public void test01() throws Exception;

    public void test02() throws Exception;

    public void test03() throws Exception;
}

实现接口 TestThreadServiceImpl.java
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class TestThreadServiceImpl implements ITestThreadService {


    @Override
    @Async("taskExecutor")
    public void test01() throws Exception{
        for (int i = 0; i < 5; i++) {
            Thread.sleep(1000);
            System.out.println("test01运行 = " + i);
        }
    }

    @Override
    @Async("taskExecutor")
    public void test02() throws Exception {
        for (int i = 0; i < 5; i++) {
            Thread.sleep(1500);
            System.out.println("test02运行 = " + i);
        }
    }

    @Override
    @Async("taskExecutor")
    public void test03() throws Exception {
        for (int i = 0; i < 5; i++) {
            Thread.sleep(2000);
            System.out.println("test03运行 = " + i);
        }
    }
}

  

控制测试 TestThreadController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestThreadController {

    @Autowired
    private ITestThreadService testThreadService;

    @GetMapping(value = "/test")
    public void test(){

        try {
            testThreadService.test01();
            testThreadService.test02();
            testThreadService.test03();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

执行结果:

test01运行 = 0
test02运行 = 0
test03运行 = 0
test01运行 = 1
test02运行 = 1
test01运行 = 2
test03运行 = 1
test01运行 = 3
test02运行 = 2
test01运行 = 4
test02运行 = 3
test03运行 = 2
test02运行 = 4
test03运行 = 3
test03运行 = 4

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yixian123.com

谢谢打赏,祝老板心想事成

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值