Java回调实现

首先要定义一个回调方法的接口:

public interface CallBackListener {
    /**
     * 回调通知函数
     */
    void callBackNotitify(String msg);
}

然后需要定义一个调用函数,用于异步调用某个方法:

public class Caller {
    private CallBackListener callBackListener;
    private Notifier notifie;
    private String question;

    /**
     * 调用
     */
    public void call() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    System.out.println("提问:=>" + question);
                    notifie.execute(Caller.this, question);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void setCallBackListener(CallBackListener callBackListener) {
        this.callBackListener = callBackListener;
    }

    public CallBackListener getCallBackListener() {
        return callBackListener;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    public Notifier getNotifie() {
        return notifie;
    }

    public void setNotifie(Notifier notifie) {
        this.notifie = notifie;
    }

    public String getQuestion() {
        return question;
    }
}

最终被调用的方法,需要调用回调函数,返回调用后的结果:

public class Notifier {
    public void execute(Caller caller, String msg) throws Exception {
        TimeUnit.SECONDS.sleep(2);
        caller.getCallBackListener().callBackNotitify("我在这.....");
    }
}

主函数调动方法如下:

public class Main {
    public static void main(String[] args) {
        Notifier notifier = new Notifier();
        Caller caller = new Caller();
        caller.setNotifie(notifier);
        caller.setQuestion("你在哪里?");
        caller.setCallBackListener(new CallBackListener() {
            public void callBackNotitify(String msg) {
                System.out.println("回复:=>" + msg);
            }
        });
        caller.call();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值