@Configuration
@EnableAsync
@Component
public class ThreadPoolConfigTest {
@Bean(name = "asyncExecutor")
public Executor getThreadPool() {
//cpu的核心数,包括超线程出来的cpu核心数
int num = Runtime.getRuntime().availableProcessors();
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(num);
taskExecutor.setMaxPoolSize(num * 5);
//阻塞队列任务
taskExecutor.setQueueCapacity(num * 2);
//线程名的前缀
taskExecutor.setThreadNamePrefix("taskExecutor->");
//初始化线程池
taskExecutor.initialize();
return taskExecutor;
}
}
创建线程任务
@Component
public class ThreadTasks {
@Async
public void startMyThreadTask(int i) throws InterruptedException {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + ": " + i);
System.out.println("startMyThreadTask: " + i);
}
}
调用
@RestController
@RequestMapping("/thread")
public class ThreadController {
@Resource
private ThreadTasks threadTasks;
@Resource
private TestService testService;
@GetMapping("test1")
public void test1() throws InterruptedException {
System.out.println("test1获取主线程名称: " + Thread.currentThread().getName());
for (int i = 0; i < 10; i++) {
threadTasks.startMyThreadTask(i);
}
System.out.println("test1执行任务完成了");
}
定义Service
@Service
public class TestService {
@Resource
private ThreadPoolTaskExecutor asyncExecutor;
public void test() {
System.out.println(Thread.currentThread().getName());
asyncExecutor.submit(() -> {
System.out.println(Thread.currentThread().getName());
System.out.println("娃哈哈哈哈哈");
});
}
}
使用Service
@RestController
@RequestMapping("/thread")
public class ThreadController {
@Resource
private ThreadTasks threadTasks;
@Resource
private TestService testService;
@GetMapping("test2")
public void test2() {
testService.test();
}
}
实例代码
@SpringBootTest
class ThreadPoolApplicationTests {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
AsyncTest asyncTest;
@Autowired
ThreadPoolTaskExecutor threadPoolTaskExecutor;
@Test
void contextLoads() throws InterruptedException {
asyncTest.hello("async注解创建");
threadPoolTaskExecutor.submit(new Thread(()->{
logger.info("threadPoolTaskExecutor 创建线程");
}));
//一定要休眠 不然主线程关闭了,子线程还没有启动
Thread.sleep(1000);
}
}
参考链接: 线程池配置及@Async异步注解