项目中线程池的应用

1、首先我们需要在配置类中将线程池作为单例bean配置

复制代码
@Configuration
public class ThreadPoolExecutorConfig {
    @Bean
    ExecutorService executorService(){
        return new ThreadPoolExecutor(
                2,
                3,
                0,
                TimeUnit.MICROSECONDS,
                new ArrayBlockingQueue<>(3),
                (r)->new Thread(r,"name"+System.currentTimeMillis()),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

}

2、 然后再对应的service中注入我们的ExecutorService

复制代码
package com.example.threaddemo.demos;

import com.example.threaddemo.mapper.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;
@Component
public class Test {


    @Autowired
    private ExecutorService executorService;
    @Autowired
    private TestMapper testMapper;


}

3、在方法中调用我们的线程池对象并且执行我们传入的任务

复制代码
package com.example.threaddemo.demos;

import com.example.threaddemo.mapper.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;
@Component
public class Test {


    @Autowired
    private ExecutorService executorService;
    @Autowired
    private TestMapper testMapper;

    public void test() {
        Future<?> submit = executorService.submit(testMapper::Test1);
        System.out.println(submit.getClass());
    }


}


//下方是mapper文件,假设在操作数据库
package com.example.threaddemo.mapper;

import org.springframework.stereotype.Component;
@Component
public class TestMapper {
    public void Test1(){
        System.out.println("Test");
    }
}

4、简述执行流程

  1. 首先程序会构建线程池
  2. 当我们使用方法引用将上方指定的mapper中的方法传入线程池的submit方法中时,实际是传入到线程池中的Runnable的run方法,程序会根据我们的run方法进行执行
  3. 使用submit方法可以获取到返回值对象Future实例,通过Future实例可以调用get方法获取到我们所期待的返回值
  4. 但是此时这个submit是阻塞式的,他会阻塞调用它的线程直到get方法成功获取到返回值,此时可以考虑使用 execute 方法
相关推荐
Sylvia-girl1 小时前
Java——抽象类
java·开发语言
Yana.nice3 小时前
Bash函数详解
开发语言·chrome·bash
Touper.4 小时前
Redis 基础详细介绍(Redis简单介绍,命令行客户端,Redis 命令,Java客户端)
java·数据库·redis
m0_535064604 小时前
C++模版编程:类模版与继承
java·jvm·c++
虾条_花吹雪5 小时前
Using Spring for Apache Pulsar:Message Production
java·ai·中间件
tomorrow.hello5 小时前
Java并发测试工具
java·开发语言·测试工具
Moso_Rx5 小时前
javaEE——synchronized关键字
java·java-ee
晓13135 小时前
JavaScript加强篇——第四章 日期对象与DOM节点(基础)
开发语言·前端·javascript
老胖闲聊5 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
张小洛5 小时前
Spring AOP 是如何生效的(入口源码级解析)?
java·后端·spring