for循环调用优化多行程处理 带返回值处理

文章讲述了在项目开发中,通过创建线程池并发调用响应时间较长的三方接口,以减少for循环调用时间过长的问题。作者使用了CountDownLatch确保所有线程执行完毕。
摘要由CSDN通过智能技术生成

在项目中遇到根据请求循环调用三方接口,结果三方接口返回时常大概25秒左右,导致for循环调用时间超长,这里需要多行程处理。直接上代码如下↓

package cn.com.bsfit.frms.workflow.application.plugins.service.server;

 

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.atomic.AtomicInteger;

 

public class Main {

 

public static void main(String[] args) {

// 模拟请求报文有10个押品;

List list = new ArrayList();

for (int i = 1; i < 11; i++) {

list.add("ss"+i);

}

 

AtomicInteger countNum = new AtomicInteger();

StringBuffer contstr = new StringBuffer();

 

long start = System.currentTimeMillis();

 

//Executors创建线程池new固定的10个线程

ExecutorService taskExecutor = Executors.newCachedThreadPool();

final CountDownLatch latch = new CountDownLatch(list.size());//用于判断所有的线程是否结束

System.out.println("个数==" + list.size());

 

for (int m = 0; m < list.size(); m++) {

final int n = m;//内部类里m不能直接用,所以赋值给n

final String ss = (String)list.get(n);

Runnable run = new Runnable() {

public void run() {

try {

System.out.println("我在执行=" + n);

// System.out.println("ss--"+ss);

String ss = getProce(""+n);

System.out.println("new ss is"+ss);

countNum.addAndGet(n);

contstr.append(ss);

} catch (Exception e) {

    e.printStackTrace(); //此处异常可根据情况 不做处理

   } finally {

latch.countDown(); //每次调用CountDown(),计数减1

}

}

};

taskExecutor.execute(run);//开启线程执行池中的任务。还有一个方法submit也可以做到,它的功能是提交指定的任务去执行并且返回Future对象,即执行的结果

}

 

boolean flag = false;

try {

 flag =latch.await(30, TimeUnit.SECONDS);

 System.out.println("flag1==="+flag);

//等待所有线程执行完毕

// latch.await();//主程序执行到await()函数会阻塞等待线程的执行,直到计数为0

} catch (Exception e) { //此处异常可根据情况 不做处理

 System.out.println(" yic了 ");

e.printStackTrace();

}finally {

  long end = System.currentTimeMillis();

  System.out.println("2总时间 = " + (end - start));

  System.out.println("countNum =="+countNum);

  System.out.println("contstr is "+contstr);

  System.out.println("flag2==="+flag);

  if(!flag) {

   System.out.println(" ------ 超时了 ------ ");

  }

taskExecutor.shutdown();//关闭线程池

//所有线程执行完毕,执行主线程

}

 

 

}

 

 

public static String getProce(String node) {

 String reStr = "";

 try {

   Thread.sleep(2000);

   reStr+=node;

  } catch (InterruptedException e) {

   e.printStackTrace();

  }

 return reStr;

}

 

}

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kanglujiushi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值