Inter-module calls
In an application system, no matter what language is used for development, there must be a gap between modules. There are several calling methods:
(1) Synchronous call
Synchronous call is the most basic and simplest A calling method. Method a() of class A calls method b() of class B. It waits for method b() to finish executing and method a() to continue.This calling method is suitable for situations where the execution time of method b() is not long, because if the execution time of method b() is long or it is directly blocked, the remaining code of method a() will It cannot be executed, which will cause the entire process to be blocked.
(2) Asynchronous call
Asynchronous call is to solve the problem of possible blocking of synchronous call, resulting in A calling method caused by the entire process being stuck.Method a() of class A calls method b() of class B by starting a new thread, and the code is then executed directly, so regardless of the execution time of method b() How long will it take for the execution of method a() to be blocked?
But in this way, since method a() does not wait for the execution of method b() to complete, when method a() requires the execution result of method b() (depending on the specific situation) It depends on the business. For some businesses, such as starting an asynchronous thread to send a WeChat notification or refreshing a cache, it is not necessary.) The execution result of method b() must be monitored in a certain way.
(3) Callback
Finally is the callback. The idea of the callback is:
Such a calling method forms the picture above, which is atwo-waycalling method.
Code example
Next let’s look at the callback code example, the code simulates It is such a scene: the teacher asks the students a question, and the students answer the teacher after thinking about it.
First define a callback interface, which has only one method tellAnswer(int answer), that is, the student tells the teacher the answer after thinking:
/** * 回调接口,原文出处http://www.cnblogs.com/xrq730/p/6424471.html */ public interface Callback { public void tellAnswer(int answer); }
Define a The teacher object implements the Callback interface:
/** * 老师对象,原文出处http://www.cnblogs.com/xrq730/p/6424471.html */ public class Teacher implements Callback { private Student student; public Teacher(Student student) { this.student = student; } public void askQuestion() { student.resolveQuestion(this); } @Override public void tellAnswer(int answer) { System.out.println("知道了,你的答案是" + answer); } }
The teacher object has two public methods:
(1) Callback interface tellAnswer(int answer), that is, the student has answered the question After that, what the teacher has to do
(2) ask question method askQuestion(), that is, ask the student a question
Then define a student interface, the student will of course solve the problem, but receive a Callback parameters, so that students know who to report to after solving the problem:
/** * 学生接口,原文出处http://www.cnblogs.com/xrq730/p/6424471.html */ public interface Student { public void resolveQuestion(Callback callback); }
Finally define a specific student named Ricky:
/** * 一个名叫Ricky的同学解决老师提出的问题,原文出处http://www.cnblogs.com/xrq730/p/6424471.html */ public class Ricky implements Student { @Override public void resolveQuestion(Callback callback) { // 模拟解决问题 try { Thread.sleep(3000); } catch (InterruptedException e) { } // 回调,告诉老师作业写了多久 callback.tellAnswer(3); } }
After solving the problem, line 16 reports the answer to the teacher.
Write a test class, which is relatively simple:
/** * 回调测试,原文出处http://www.cnblogs.com/xrq730/p/6424471.html */ public class CallbackTest { @Test public void testCallback() { Student student = new Ricky(); Teacher teacher = new Teacher(student); teacher.askQuestion(); } }
The code running result is just one line:
知道了,你的答案是3
Briefly summarize and analyze this example That is:
(1) The teacher calls the method resolveQuestion of the student interface and asks the student a question
(2) After the student solves the problem, he calls the teacher’s callback method tellAnswer
Such a set of processes constitutes a two-way calling relationship.
Code Analysis
Analyze the above code. I have made two layers of abstraction for the above code:
(1) Abstract the teacher
(2) Abstract the students
This example is a typical example that reflects the role of the interface. The reason why I say this is because I think that some friends may not understand the benefits of interfaces. Friends who do not understand the benefits of interfaces can focus on this example to understand more.
To sum up,The core of the callback is that the callback party passes itself, this, to the caller, so that the caller can tell the callback after the call is completed the information it wants to know. Callback is an idea and a mechanism. As for how to implement it, how to implement callback elegantly and with high scalability through code depends on the developer's personal level and the developer's understanding of the business. .
Synchronous callbacks and asynchronous callbacks
In the above example, someone may ask this question:
What kind of callback is needed for this example? Using synchronous calling, wouldn’t it be great if the student object answers the question and directly returns the answer to the teacher object?
There is no problem in raising this question. This question can be understood from two angles.
First of all, what if the teacher doesn’t just want answers from students?
Maybe this teacher is a teacher who prefers to listen to students' problem-solving ideas. Before getting the students' answers, the teacher would like to know the students' names and students' problem-solving ideas. Of course, some people can say that, then I can Wouldn't it be nice to define an object and add the student's name and solution ideas? In my opinion, there are two problems with this statement:
(1) If the teacher wants more and more data, the returned objects must be larger and larger, and using callbacks can separate the data. Put a batch of data in the callback method for processing. As for which data depends on the specific business, if you need to add return parameters, just add them directly in the callback method
(2) Unable to solve the problem that the teacher wants to get students Name, student's problem-solving ideas precede the student's answer
So I think there is no need to use a callback to simply return a certain result and you can directly use synchronous calls, but if there are multiple types of data that need to be processed and Data is classified into primary and secondary data, so using callbacks would be a more appropriate choice. Prioritized data should be processed first in the callback method.
Another angle of understanding is more important, which is the synchronous callback and asynchronous callback mentioned in the title. The example is a synchronous callback, which means that the teacher asks Ricky a question, Ricky gives the answer, the teacher asks the next classmate, and after getting the answer, continues to ask the next classmate. This is a normal scenario, but if I change the scenario Take a look:
The teacher did not want to ask questions like One-By-One. Instead, he asked the five students Ricky, Mike, Lucy, Bruce, and Kate at the same time, letting the students think for themselves, which student should think? When you are done, just tell the teacher the answer directly.
This scenario is equivalent to saying that after students have finished thinking about the problem, they must have a way to tell the teacher. There are two solutions:
(1) Use Future Callable method, waiting for the asynchronous thread execution result, which is equivalent to a variant of synchronous call, because its essence is that the method returns a result, that is, the student's answer
(2) Using asynchronous callback, the student finishes answering the question, Just call the callback interface method and tell the teacher the answer. Since the teacher object is abstracted into the Callback interface, this approach has very good scalability. As mentioned before, even if the teacher changes one after another, for the students, the only thing they care about is calling the Callback interface. Just return the necessary information
For more related knowledge, please pay attention to thejava basic tutorialcolumn
The above is the detailed content of Introduction to Java callback mechanism. For more information, please follow other related articles on the PHP Chinese website!