看到一个场景使用了java回调方法,遂提起兴趣花了时间去了解回调的大概过程。
试着大概想象以下3过程,
1,老师向学生提了一个问题
2,学生花费时间去思考
3,然后学生向老师回答问题。
以上的三个过程
过程1,老师向学生提问:
public class TestCallBack {
public static void main (String[] args) {
Student student = new Student();
Teacher teacher = new Teacher(student);
System.out.println("main方法中:老师向学生提问");
teacher.askQuestion();
}
}
过程2,学生需要时间去思考:Student类
public class Student{
public void resolveQuestion(Teacher teacher) {
try {
System.out.println("Student对象里:学生在思考问题中,需要时间6秒);
Thread.sleep(6000);
} catch (InterruptedException e) {}
teacher.tellAnswer("这是在Student类中给老师的回答");
}
}
过程3,学生把回答呈递给老师:Teacher类
public class Teacher{
private Student student;
public Teacher (Student student) {
this.student = student;
}
public void askQuestion () {
student.resolveQuestion(this);
}
public void tellAnswer(String str) {
System.out.println("Teacher对象里: " + str);
}
}
可以运行main,输出为:
main方法中:老师向学生提问
Student对象里:学生在思考问题中,需要时间6秒
Teacher对象里: 这是在Student类中给老师的回答
想要理解回调,必须抓住一点,站在单线程的角度去思考
1,在main方法里,new出了一个student与一个teacher对象,然后调用teacher对象的askQuestion方法;
2,teacher对象的askQuestion方法又调用了student对象的resolveQuestion方法;
3, 在student对象里完成了resolveQuestion后,回调了teacher对象里的tellAnswer方法;
上述过程3,完成了最重要的一步回调。
把整个流程再简单显示:
teacher.askQuestion->student.resolveQuestion->teacher.tellAnser
就是执行从A类到B类又回到A类的过程。
以上是本人对java回调的理解,希望对大家有帮助!