首先要定义一个回调方法的接口:
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();
}
}