Spring线程池ThreadPoolTaskExecutor使用

为什么使用线程池?

  • 降低系统资源消耗,通过重用已存在的线程,降低线程创建和销毁造成的消耗;
  • 提高系统响应速度,当有任务到达时,通过复用已存在的线程,无需等待新线程的创建便能立即执行;
  • 方便线程并发数的管控,因为线程若是无限制的创建,可能会导致内存占用过多而产生OOM,并且会造成cpu过度切换(cpu切换线程是有时间成本的(需要保持当前执行线程的现场,并恢复要执行线程的现场)
  • 提供更强大的功能,延时定时线程池

参考博客:https://blog.csdn.net/u012060033/article/details/111934507



简单使用:
参考博客:https://blog.csdn.net/weixin_45866737/article/details/122539694

创建线程池

MyThreadPool .java

@Configuration
public class MyThreadPool {
    //ThreadPoolTaskExecutor不会自动创建ThreadPoolExecutor,需要手动调initialize才会创建。如果@Bean就不需手动,会自动InitializingBean的afterPropertiesSet来调initialize
    @Bean("myExecutor")
    public Executor createJobExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 线程池活跃的线程数
        executor.setCorePoolSize(20);
        // 设置线程队列最大线程数
        executor.setMaxPoolSize(40);
        // 设置等待队列大小
        executor.setQueueCapacity(200);
        // 线程池维护线程所允许的空闲时间
        executor.setKeepAliveSeconds(60);
        // 线程前缀名称
        executor.setThreadNamePrefix("myExecutor---: ");
        executor.initialize();
        return executor;
    }
}

service层

@Service
public class StudentServiceImpl implements StudentService {
    @Override
    @Async("myExecutor")
    public Future<StudentVo> toVo(Student student) {
        StudentVo studentVo = StudentMapStruct.INSTANCE.studentToVo(student);
		// 业务操作
        return new AsyncResult<>(studentVo);
    }
}

controller层:

@Api(tags = "学生实体类转vo接口")
@RestController
@RequestMapping(value = "/trans")
public class StudentController {
    @Autowired
	StudentServiceImpl studentService;
	
    @ResponseBody
    @PostMapping("/students")
    @ApiOperation(value = "测试接口")
    public ResponseEntity<StudentResponse> testStudent(@ApiParam("学生请求对象实体类") @RequestBody Student student){

        Future<StudentVo> studentVo = studentService.toVo(student);
        while (studentVo.isDone()) {
            break;
        }
        StudentResponse studentResponse = StudentMapStruct.INSTANCE.voToResponse(studentVo.get());
        return new ResponseEntity(studentResponse, HttpStatus.OK);
    }
}

你可能感兴趣的:(spring,python,java)