多线程如何监控完成状态

多线程情况下,如何非阻塞的获取所有线程执行完的结果,包括异常处理

场景

处理大量数据时或者比较耗时的业务逻辑,但这个处理过程又无需立即进行返回,只是当处理完了的时候通知一声,统一收集错误信息。

模拟现场场景

比如你是公司的boss,现在有5名员工,你要下发任务给这5个员工,这5名员工可能做一样的事情,但每个人处理的时间又不一样,
所以你必须等他们处理完相关任务之后,才能分配其他工作,或者结束工作。

那么每个员工执行完了,会通知你一声,待到最后一个员工通知完了,算是结束。

但是呢,难免有些人做的快和慢,而且有些还可能做不完,所以最后要统一检查一遍,并且看看都有谁没做完。

代码设计

需要有一个统一处理的boss,5名员工,就为5个线程,那么最起码有个线程池子

1.首先需要定义一个线程池子

设置线程大小为5

private static final ExecutorService POOL = Executors.newFixedThreadPool(5);

2.执行任务

每个线程有独立的任务,执行完之后,要通知boss,并且准备一个问题收集器也就是异常列表

List<Throwable> throwableList = new ArrayList<>();

ps: 但是要考虑会不会占用内存过多,如果业务量过大的话

线程1定义

// 一号员工
CompletableFuture<Void> employee1 = CompletableFuture.runAsync(() -> {
    try {
        // 工作花费的时间
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}, POOL).whenComplete((Void, throwable)-> {
    // 完成后表示自己完成了
    System.out.println("一号员工完成了任务");
    if (throwable != null) throwableList.add(throwable);
});

线程2定义

// 二号员工
CompletableFuture<Void> employee2 = CompletableFuture.runAsync(() -> {
    try {
        // 工作花费的时间
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}, POOL).whenComplete((Void, throwable)-> {
    // 完成后表示自己完成了
    System.out.println("二号员工完成了任务");
    if (throwable != null) throwableList.add(throwable);
});

线程3定义

// 三号员工
CompletableFuture<Void> employee3 = CompletableFuture.runAsync(() -> {
    try {
        // 工作花费的时间
        Thread.sleep(3000);
        // 干了一会,我不服,为啥给你打工,这边直接拒绝工作,直接抛出异常
        throw new RuntimeException("三号员工说:老子不想工作,只想玩乐");
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}, POOL).whenComplete((Void, throwable)-> {
    // 完成后表示自己完成了
    System.out.println("三号员工没有完成,态度不对");
    if (throwable != null) throwableList.add(throwable);
});

线程4定义

// 四号员工
CompletableFuture<Void> employee4 = CompletableFuture.runAsync(() -> {
    try {
        // 工作花费的时间
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}, POOL).whenComplete((Void, throwable)-> {
    // 完成后表示自己完成了
    System.out.println("四号员工完成了任务");
    if (throwable != null) throwableList.add(throwable);
});

线程5定义

// 五号员工
CompletableFuture<Void> employee5 = CompletableFuture.runAsync(() -> {
    try {
        // 工作花费的时间
        Thread.sleep(5000);
        throw new RuntimeException("五号员工说:家中有事,需要先回家咯,不干了");
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}, POOL).whenComplete((Void, throwable)-> {
    // 完成后表示自己完成了
    System.out.println("五号员工没有完成,家中有事,干不完了");
    if (throwable != null) throwableList.add(throwable);
});

3.boss收到结果

每次对线程执行完毕进行日志打印记录

// boss获取结果
CompletableFuture.allOf(employee1, employee2, employee3, employee4, employee5)
        .whenComplete((Void, throwable)->{
            System.out.println("收到完成任务通知了");
            System.out.println("让我看看,结果咋样:" + throwableList);
            // 关闭池子
            POOL.shutdown();
        });

4.执行结果

在这里插入图片描述

结论

使用CompletableFuture进行编排处理异步任务是一种很好的方式,可以根据实际业务需求使用runAsync()、supplyAsync()方法,每次执行完都使用whenComplete进行结果处理,包括异常的处理。

最重要的是对于所有任务完成之后使用了allOf()针对结果之后做出统一处理,且因为多个异常我们都存入到了list中,所以可以针对异常再次处理,那么allOf()中的throwable其实只支持一个异常处理,面对多个异常的时候,就无法接收

同时他还不能知道是哪个线程给出来的异常,所以处理异常时候要多多注意关键信息。

在多线程获取每个线程处理的结果使用起来还是比较合适的。

完整代码

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 多线程完成任务之后进行通知
 */
public class ThreadCompletionNotify {

    private static final ExecutorService POOL = Executors.newFixedThreadPool(5);

    public static void main(String[] args) {
        System.out.println("boss开始分配工作");
        List<Throwable> throwableList = new ArrayList<>();
        // 一号员工
        CompletableFuture<Void> employee1 = CompletableFuture.runAsync(() -> {
            try {
                // 工作花费的时间
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, POOL).whenComplete((Void, throwable)-> {
            // 完成后表示自己完成了
            System.out.println("一号员工完成了任务");
            if (throwable != null) throwableList.add(throwable);
        });

        // 二号员工
        CompletableFuture<Void> employee2 = CompletableFuture.runAsync(() -> {
            try {
                // 工作花费的时间
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, POOL).whenComplete((Void, throwable)-> {
            // 完成后表示自己完成了
            System.out.println("二号员工完成了任务");
            if (throwable != null) throwableList.add(throwable);
        });

        // 三号员工
        CompletableFuture<Void> employee3 = CompletableFuture.runAsync(() -> {
            try {
                // 工作花费的时间
                Thread.sleep(3000);
                // 干了一会,我不服,为啥给你打工,这边直接拒绝工作,直接抛出异常
                throw new RuntimeException("三号员工说:老子不想工作,只想玩乐");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, POOL).whenComplete((Void, throwable)-> {
            // 完成后表示自己完成了
            System.out.println("三号员工没有完成,态度不对");
            if (throwable != null) throwableList.add(throwable);
        });

        // 四号员工
        CompletableFuture<Void> employee4 = CompletableFuture.runAsync(() -> {
            try {
                // 工作花费的时间
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, POOL).whenComplete((Void, throwable)-> {
            // 完成后表示自己完成了
            System.out.println("四号员工完成了任务");
            if (throwable != null) throwableList.add(throwable);
        });

        // 五号员工
        CompletableFuture<Void> employee5 = CompletableFuture.runAsync(() -> {
            try {
                // 工作花费的时间
                Thread.sleep(5000);
                throw new RuntimeException("五号员工说:家中有事,需要先回家咯,不干了");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, POOL).whenComplete((Void, throwable)-> {
            // 完成后表示自己完成了
            System.out.println("五号员工没有完成,家中有事,干不完了");
            if (throwable != null) throwableList.add(throwable);
        });

        System.out.println("boss任务分配完了,开始工作吧,小老弟们");

        // boss获取结果
        CompletableFuture.allOf(employee1, employee2, employee3, employee4, employee5)
                .whenComplete((Void, throwable)->{
                    System.out.println("收到完成任务通知了");
                    System.out.println("让我看看,结果咋样:" + throwableList);
                    // 关闭池子
                    POOL.shutdown();
                });

        System.out.println("到此主线程执行完了。。。");
        System.out.println("----------------------------------------------------");
    }
}

" + throwableList);
                    // 关闭池子
                    POOL.shutdown();
                });

        System.out.println("到此主线程执行完了。。。");
        System.out.println("----------------------------------------------------");
    }
}

  • 16
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值