Reprint please indicate the source
Author: Xiao Watanabe
Article Address: https://greatestrabit.github.io/2016/03/29/callback/
1. Callbacks in a literal sense
class a {/** * ask questions * @author [email protected] * @param b * @param question */public void ask (final b b, final string question) {b.answer (this, question);} /** * processing Results * @author [email protected] * @param answer */ Public void processresult (final string answer) {system.out.println (answer);}} class b {/** * calculation results * @author [email protected] * @param a * @param question */public void answer (final a a, final string question) {if (Question.equals ("what is the answer to Life, the universe and everything? ")) {a.processresult ("42");}} /** * Mutual calls * @author [email protected] * */public class Syncobjectcallback {public static void main (Final string[] args) {B b = new b (); A a = new a (); A.ask (b, "what is the answer to life, the universe and everything? ");}}
2. Object-oriented callbacks
In the above notation, the object of B is passed only in the method. In fact, the B object then calls a method in a, which should be more than just a single method, but rather a part of a. That is, the above is not "object-oriented", let us change:
Class a {private final b b;public a (final b b) {this.b = b;} Public void ask (final string question) {this.b.answer (this, question);} Public void processresult (final string answer) {system.out.println (answer);}} Class b {public void answer (final a a, final string question) {if (Question.equals ("What is the answer to life, the universe and everything? ")) {a.processresult ("42");}} /** * object-oriented mutual invocation * @author [email protected] * */public class syncoocallback {public static void main (Final string[] args) {B B = new b (); A a = new a (b); A.ask ("what is the answer to life, the Universe and everything? ");}}
3. Interface-oriented callbacks
The above two examples, it is estimated that no one will admit that is also a callback. Because there is no egg to use. However, this process is important for understanding callbacks. In fact, the callback is really useful in its "predictive" ability.
Let's expand and imagine. Assuming B in the example above, a sudden awakening after providing a lot of services for a and wanting to serve more objects, B becomes the server. and rules. What is the rule, that is, to provide services to the server, The other party must have a recvanswer interface for the server to call, so that the server can pass the results back to the client. How do you make the rules? Through interface. as follows:
/** * sends out a request for an interface to implement, methods * @author to implement the results [email protected] * */public interface iclient {void recvanswer (string answer);} /** * responding to requesters, i.e. service providers * @author [email protected] * */public class server {public void answer (final iclient client, final string question) {if (Question.equals ("What is the answer to life, the universe and everything? ")) {calclating (); Client.recvanswer ("42");}} Private void calclating () {try {thread.sleep (New random (). NEXTINT (5000));} catch (interruptedexception e) {e.printstacktrace ();}} /** * to process the request result * @author [email protected] * */ public class clientsync implements iclient {private final server Server;puBlic clientsync (Final server server) {this.server = server;} Public void ask (final string question) {this.server.answer (this, question);} @Overridepublic void recvanswer (final string answer) {system.out.println (answer);}} /** * interface-oriented synchronous callbacks * @author [email protected] * */public class SyncInterfaceCallback {/** * How to implement using internal classes * @author [email Protected] */private static void innermain () {server server = new server (); Server.answer (New iclient () {@Overridepublic void recvanswer (final String answer) {system.out.println (answer);}}, "what is the answer to Life, the universe and everything? ");} Public static void main (Final string[] args) {Server server = new server (); Clientsync client = new clientsync (server); Client.ask ("What is the answer to life, the universe and everything? "); Innermain ();}}
Note that the interface iclient should actually belong to the server side, which is a server-developed interface that needs to be implemented by the client, although it looks close to the client.
Why is there a "predictive" ability? Imagine another scene. Server is now a low-level service, and the underlying service knows that one day there will be a top service to beg for data, but how is the data going up? The bottom can promise that only you implement the IClient interface, I will call the Recvanswer method, Send the data up. Now the bottom layer can also call the high-level method, there is a "predictive" ability it?
4. Asynchronous callbacks
public class clientasync implements iclient {private final server Server;public clientasync (Final server server) {this.server = server;} /** * making requests * @author [email protected] * @param question in the thread */public void ask (final string question) {new thread (new Runnable () {@Overridepublic void run () {server.answer (clientasync.this, question);}). Start ();} @Overridepublic void recvanswer (final string answer) {system.out.println (answer);}} /** * interface-based asynchronous callbacks, each time you create a new thread * @author [email protected] * */ public class asyncinterfacecallback {/** * uses the implementation of the inner class, which is visible here callback Hell * @author [email protected] */private static void innermain () {Server server = new server ();new Thread (new runnable () {@Overridepublic void run () {server.answer (New iclient () {@Overridepublic void recvanswer (final string answer) {system.out.println ( Answer);}}, "what is the answer to life, the universe and Everything ");}). Start (); System.out.println ("Asked ! waiting for the answer ..."); Public static void main (Final string[] args) {server server = new server (); Clientasync client = new clientasync (server); Client.ask ("What is the answer to life, the universe and everything? "); System.out.println ("Asked ! waiting for the answer ..."); Innermain ();}}
5. Thread pool Asynchronous callback
Each time the creation of a new thread consumes a lot of resources, in order to reuse the thread, using the thread pool to manage the asynchronous call, this time requires the client not only to implement the IClient interface, but also a task to be executed by the thread pool, as follows:
/** * specifically used to perform the requested task for the thread pool call * @author [email protected] * */public Class clientrunnable implements iclient, runnable {private final server server;private final String question;private final int id;public Clientrunnable (final server server, final string question, final int ID) {this.server = server;this.question = question;this.id = id;} @Overridepublic void recvanswer (final string answer) {system.out.println ("Clinet " + this.id + " got answer: " + answer);} @Overridepublic void run () {server.answer (clientrunnable.this, this.question);}} /** * thread pool-based asynchronous callback * @author [email protected] * */public class ThreadpoolCallback {public static Void main (Final string[] args) {ExecutorService es = Executors.newcachedthreadpool (); Server server = new server ();for (int i = 0; i < 100 ; i++) {clientrunnable cr = new clientrunnable (server, "What is The answer to life, the universe and everything? ", i); Es.execute (CR); System.out.println ("client " + i + " asked !");} Es.shutdown ();}}
At this point, we implement the thread pool asynchronous callback.
Full source please visit: GitHub
This article from the "Dream do not know is a guest" blog, please be sure to keep this source http://greatestrabit.blog.51cto.com/11375247/1760245
Take you step by step implement thread pool asynchronous callback