后端——》使用ThreadPoolExecutor线程池处理并发请求

2023-05-16

使用场景

本地有一个List,需要把list中的每一条数据传第三方公司的A、B、C、D、E、F共六个接口。那么如果一个数据传给A、再传给B、…最后传给E,那么会耗费很长时间。如果开6个线程,每个线程只访问A-E中的一个接口,那么时间就会缩短6倍。

实现方式以及使用

  1. 定义一个线程池

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();
    }

}
  1. 使用
/*这个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个接口请求

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

后端——》使用ThreadPoolExecutor线程池处理并发请求 的相关文章

随机推荐