回调函数判断多条线程是否执行完成简单实现-非线程安全

回调方法接口

    先添加一个回调方法接口

/**
 * 回调接口
 */
public interface CallBack {

    /**
     * 回调函数
     *
     * @param result
     */
    void call(String result);

}

调用方

    多线程调用具体处理逻辑方法,和回调函数的具体实现,默认有10次处理,当数量增大的时候存在线程安全问题

/**
 * 调用方
 * 实现回调接口
 */
public class Caller implements CallBack {

    //用于计数
    private int length, count;

    /**
     * 构造函数
     */
    public Caller() {
        length = 10;
        count = 0;
    }

    /**
     * 要调用的Deal方法的函数,模拟length条线程进行处理
     */
    public void deal() {
        Executor dev = new Executor();
        for (int i = 0; i < length; i++) {
            int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //调用具体逻辑,传入此对象
                    dev.deal(Caller.this, finalI);
                }
            }).start();
        }
    }

    /**
     * 回调函数处理逻辑,等所有线程处理完,进行后续逻辑处理
     *
     * @param result
     */
    public void call(String result) {
        synchronized (Caller.class) {
            //输出执行状态
            System.out.println(result);
            length--;
            count++;
            System.out.println("执行线程数量统计=" + count);
            if (length == 0) {
                System.out.println("所有线程执行完毕");
            }
        }
    }

}

被调用方

    执行具体的处理逻辑,并回调方法,通知调用方自己执行完成

/**
 * 执行方
 * 调用回调函数
 */
public class Executor {

    /**
     * 处理逻辑
     * 并调用回调方法
     *
     * @param callBack
     * @param index
     */
    public void deal(CallBack callBack, int index) {
        System.out.println("第" + index + "条线程开始执行");
        //随机数模拟方法执行一段时间
        long m = new Random().nextInt(5);
        try {
            Thread.sleep(m * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("sleep异常");
        }
        String result = "第" + index + "条线程执行完成,执行" + m + "秒";
        //执行完成调用回调函数
        callBack.call(result);
    }

}

测试程序

/**
 * 测试类
 *
 * @author will
 */
public class CallBackTest {

    public static void main(String[] args) {
        Caller master = new Caller();
        master.deal();
    }
}

执行结果

 

参考:https://blog.csdn.net/jim1451/article/details/84036930 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值