【Java多线程】多线程实现异步调用结果返回

前言

在我们的业务中很可能会碰到需要执行一段时间的任务,并且如果同步的话就会造成一些无谓的等待。因此可以使用异步调用的方法,不阻塞当前其他任务的执行。

小栗子

首先我们先要创建一个线程池,可以根据自己的需求创建,什么IO密集型参数设置,CPU密集型参数的设置。这里我们仅仅想让10个任务一起跑。

ExecutorService threadPool = new ThreadPoolExecutor(
                        10,
                        10,
                        0,
                        TimeUnit.SECONDS,
                        new SynchronousQueue<>(),
                        new ThreadPoolExecutor.AbortPolicy());

然后模拟下需要异步调用的业务的执行,这里我的n给不同线程设置了不同的执行时间,在判断超时时,会有部分线程无法完成任务。
AtomicInteger atomicInteger = new AtomicInteger(5);
List<Future<Integer>> futures = new ArrayList<>(); //存储结果
for (int i = 0; i < 10; i++) {
            Future<Integer> submit = completionService.submit(() -> {
                int n = atomicInteger.getAndIncrement();
                int h = 0;
                for (int j = n * 10; j < n * 10 + n; j++) {
                    h += j;
                    TimeUnit.SECONDS.sleep(1); //暂停线程1s
                }
                return h;

            });
            futures.add(submit);
        }

现在执行下其他的业务操作。

然后设置一些调用其他接口超时的时间,避免过长等待并开始获取下调用的结果。

		Set<AjaxResult> flags = new HashSet<>();
        List<AjaxResult> FAILS =new LinkedList<>();
        long startTime = System.currentTimeMillis();
        long timeout = 1000 * 10;
         while (flags.size()+FAILS.size()<futures.size()) {
            for (Future<Integer> o : futures) {
                if (System.currentTimeMillis() - startTime > timeout ){// 如果超时采取一定措施,或者返回一个失败。
                    FAILS.add(new AjaxResult("fail",0));
                    if(flags.size()+FAILS.size()>=futures.size()){
                        break;
                    }
                    continue;
                }
                if (o.isDone()) {
                    flags.add(new AjaxResult("success", o.get()));
                }
            }

         }
        long endTime = System.currentTimeMillis();

这里将结果分失败和成功进行存储。并记录处理的时间


接下来看下最后输出结果

		System.out.println("执行结束");
        System.out.println("耗时" + (endTime - startTime));
        System.out.println("结果" + flags.toString());
        System.out.println("失败" + FAILS.toString());
        System.exit(0);

在这里插入图片描述
本方法纯属瞎玩,仅供参考。

下面是全部的代码

public class InitConfig {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService threadPool = new ThreadPoolExecutor(
                        10,
                        10,
                        0,
                        TimeUnit.SECONDS,
                        new SynchronousQueue<>(),
                        new ThreadPoolExecutor.AbortPolicy());
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(threadPool);
        AtomicInteger atomicInteger = new AtomicInteger(5);
        List<Future<Integer>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<Integer> submit = completionService.submit(() -> {
                int n = atomicInteger.getAndIncrement();
                int h = 0;
                for (int j = n * 10; j < n * 10 + n; j++) {
                    h += j;
                    TimeUnit.SECONDS.sleep(1); //暂停线程1s
                }
                return h;

            });
            futures.add(submit);
        }
        Set<AjaxResult> flags = new HashSet<>();
        List<AjaxResult> FAILS =new LinkedList<>();
        long startTime = System.currentTimeMillis();
        long timeout = 1000 * 10;
         while (flags.size()+FAILS.size()<futures.size()) {
            for (Future<Integer> o : futures) {
                if (System.currentTimeMillis() - startTime > timeout ){
                    FAILS.add(new AjaxResult("fail",0));
                    if(flags.size()+FAILS.size()>=futures.size()){
                        break;
                    }
                    continue;
                }
                if (o.isDone()) {
                    flags.add(new AjaxResult("success", o.get()));
                }
            }

         }
        long endTime = System.currentTimeMillis();
        System.out.println("执行结束");
        System.out.println("耗时" + (endTime - startTime));
        System.out.println("结果" + flags.toString());
        System.out.println("失败" + FAILS.toString());
        System.exit(0);
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    @EqualsAndHashCode
    static class AjaxResult {
        private String ret;
        private Integer data;
    }


}
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值