java回调
A的a调用B的b,b执行完后会自己调用callback传入答案,实现回调
接口Callback
public interface Callback {
void tellYourAnswer(String name,int answer);
}
老师-A方
public class Teacher implements Callback {
private Student student;
public Teacher(Student student) {
this.student = student;
}
//提问题
public void makeQuestion() {
//加个线程-异步回调
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("回答一下,这个问题");
//学生计算,解答,参数是记录将答案告诉上级
student.haveQuestion(Teacher.this);
}
}).start();
}
//接口方法,得到学生的解答后执行
@Override
public void tellYourAnswer(String name, int answer) {
System.out.println(name + " 同学,你的回答是 " + answer);
}
}
学生-抽象成接口
public interface Student {
void haveQuestion(Callback callback);
}
一个学生-计算
public class Rickey implements Student {
private String name;
public Rickey(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void haveQuestion(Callback callback) {
try{
Thread.sleep((long) (Math.random()*2));
}catch (InterruptedException e){
e.printStackTrace();
}
//将答案告诉老师,回调
callback.tellYourAnswer(this.getName(), (int) (Math.random()*10));
}
}
测试:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class CallbackTestTest {
@org.junit.jupiter.api.Test
public void myTest1() {
Student rickey1 = new Rickey("r1");
Student rickey2 = new Rickey("r2");
Student rickey3 = new Rickey("r3");
Student rickey4 = new Rickey("r4");
Student rickey5 = new Rickey("r5");
List<Student> list = new ArrayList<>();
list.add(rickey1);
list.add(rickey2);
list.add(rickey3);
list.add(rickey4);
list.add(rickey5);
for (Iterator<Student> it = list.iterator(); it.hasNext(); ) {
Student r = it.next();
Teacher teacher = new Teacher(r);
teacher.makeQuestion();
}
}
参考博客:
同步调用/异步调用:
https://blog.csdn.net/o15277012330o/article/details/79271385
经典例子,直接概括
https://blog.csdn.net/xiaanming/article/details/8703708
同步调用/异步调用/回调: