项目中线程池实战使用
目录
废话不说,直接上代码
controller层代码
package com.zh.zcy.controller;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zh.zcy.config.Message;
import com.zh.zcy.dto.SyncConsultDto;
import com.zh.zcy.dto.SyncFavoriteDto;
import com.zh.zcy.dto.SyncPolicyMatchDto;
import com.zh.zcy.dto.SyncViewDto;
import com.zh.zcy.entity.ZcySyncOperation;
import com.zh.zcy.service.FrontJsonService;
import com.zh.zcy.service.ThreadService;
import com.zh.zcy.untils.SendUrlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* <p>
* 接口转发 前端控制器
* </p>
*
* @author zxl
* @since 2023-02-15
*/
@RestController
@RequestMapping("zcy/wxRecord")
public class FrontJsonController {
@Autowired
private ThreadService threadService;
@GetMapping("/threadTest/{id}")
public String threadTest(@PathVariable String id){
// 执行任务1
threadService.sendTask1();
// 执行任务2 都是同步执行的
threadService.sendTask2();
return id;
}
}
线程池配置类
package com.zh.zcy.config;
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;
@Configuration
@EnableAsync //开启多线程
public class ThreadPoolConfig {
@Bean("taskExecutor")
public Executor asyncServiceExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 设置核心线程池数
executor.setCorePoolSize(5);
// 设置最大线程池数
executor.setMaxPoolSize(20);
// 配置队列大小
executor.setQueueCapacity(Integer.MAX_VALUE);
// 设置线程活跃时间(秒)
executor.setKeepAliveSeconds(60);
// 设置线程默认名字
executor.setThreadNamePrefix("线程池名称");
// 等所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
// 执行初始化
executor.initialize();
return executor;
}
}
业务代码类
这里都以睡眠时长代替执行业务逻辑时长
@Async要和@Bean名称一致
package com.zh.zcy.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class ThreadService {
@Async("taskExecutor")
public void sendTask1(){
try {
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+"任务1执行完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Async("taskExecutor")
public void sendTask2(){
try {
Thread.sleep(7000);
System.out.println(Thread.currentThread().getName()+"任务2执行完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
持续更新。。。