1、引言
在开发中,有时会遇到批量处理的业务。如果单线程处理,速度会非常慢,可能会导致上游超时。这是就需要使用多线程开发。
创建线程时,应当使用线程池。一方面避免了处理任务时创建销毁线程开销的代价,另一方面避免了线程数量膨胀导致的过分调度问题,保证了对内核的充分利用。
可以使用J.U.C提供的线程池:ThreadPoolExecutor类。在Spring框架中,也可以使用ThreadPoolTaskExecutor类。ThreadPoolTaskExecutor其实是对ThreadPoolExecutor的一种封装。
2、使用ThreadPoolExecutor类
假设现有业务,输入Input类,输出Output类:
@Data
@AllArgsConstructor
public class Input {
int i;
}
@Data
@AllArgsConstructor
public class Output {
boolean success;
String s;
}
这里@Data与@AllArgsConstrutor使用了Lombok工具
处理方法:
public Output singleProcess(Input input) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrac