使用场景
本地有一个List,需要把list中的每一条数据传第三方公司的A、B、C、D、E、F共六个接口。那么如果一个数据传给A、再传给B、…最后传给E,那么会耗费很长时间。如果开6个线程,每个线程只访问A-E中的一个接口,那么时间就会缩短6倍。
实现方式以及使用
- 定义一个线程池
import java.util.concurrent.*;
public class CommonThreadPool {
private static ExecutorService exec = new ThreadPoolExecutor(50, 100, 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10000),
new ThreadPoolExecutor.CallerRunsPolicy());
public static void execute(Runnable command) {
exec.execute(command);
}
/**
* 子线程执行结束future.get()返回null,若没有执行完毕,主线程将会阻塞等待
* @param command
* @return
*/
public static Future submit(Runnable command) {
return exec.submit(command);
}
/**
* 子线程中的返回值可以从返回的future中获取:future.get();
* @param command
* @return
*/
public static Future submit(Callable command) {
return exec.submit(command);
}
public static void shutdown(){
exec.shutdown();
}
}
- 使用
/*这个example方法是主线程*/
public String example (){
/*这是我要操作的数据源list*/
List<TempUser> tempUserList = new ArrayList<>();
/*开启6个线程,每个线程分别请求一个接口,
ParentImpl是父类,请求接口时公用的部分,此处抽象出来了
childOneImpl-childSixImpl每个子接口继承父类,实现高可用*/
List<ParentImpl> duHuiTiTingInsureList = new ArrayList<>();
duHuiTiTingInsureList.add(childOneImpl);
duHuiTiTingInsureList.add(childTwoImpl);
duHuiTiTingInsureList.add(childThreeImpl);
duHuiTiTingInsureList.add(childFourImpl);
duHuiTiTingInsureList.add(childFiveImpl);
duHuiTiTingInsureList.add(childSixImpl);
/*定义一个线程执行的future的list,方便让主线程后续操作等待子线程*/
List<Future> futureList = new ArrayList<>();
List syncResultList = Collections.synchronizedList(tempUserList);
for (ParentImpl childImpl : duHuiTiTingInsureList) {
/*调用submit方法开启子线程*/
Future future = CommonThreadPool.submit(new Runnable() {
@Override
public void run() {
/*执行业务操作*/
doSend(childImpl, syncResultList);
}
});
futureList.add(future);
}
/*遍历futureList通过get方法让主线程等待子线程*/
try {
for (Future future : futureList) {
future.get();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
log.info(e.getMessage());
log.info(e.getStackTrace().toString());
}
/*6个子线程已经结束,所有数据均已请求接口完毕,继续执行主线程剩余操作...*/
}
/*业务方法*/
public void doSend(ParentImpl childImpl,List syncResultList){
for (TempUser tempUser: tempUserList) {
/*执行请求接口的业务方法*/
childImpl.request(tempUser)
}
}
效果展示

可以看到,在同一秒内,程序同时处理了6个接口请求
本文介绍了在Java中如何使用ThreadPoolExecutor线程池来并发处理接口请求,通过创建线程池,将原本串行的接口调用改为并行,从而显著提高效率,将处理时间缩短至原来的六分之一。

1261

被折叠的 条评论
为什么被折叠?



