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、简述执行流程
- 首先程序会构建线程池
- 当我们使用方法引用将上方指定的mapper中的方法传入线程池的submit方法中时,实际是传入到线程池中的Runnable的run方法,程序会根据我们的run方法进行执行
- 使用submit方法可以获取到返回值对象Future实例,通过Future实例可以调用get方法获取到我们所期待的返回值
- 但是此时这个submit是阻塞式的,他会阻塞调用它的线程直到get方法成功获取到返回值,此时可以考虑使用 execute 方法