Asynchronous callback, originally in C # is a very simple and elegant thing, unexpectedly in the Java world, but so cumbersome, first look at the following class diagram:
First define a callbacktask, as the outer face of the project, the main work for start to start an asynchronous operation, but the real work is callbackbody, it is inside the execute is the real thing to deal with, if successful, then trigger Onsucess, Otherwise, the onfailure is triggered.
Callbackapp as the final stage of the run, which has to run a separate thread, to start callbacktask, so that it does not block the subsequent processing.
Callbackbody:
Package Com.cnblogs.yjmyzz.test.callback;public abstract class Callbackbody { void onsuccess (Object context) { System.out.println ("onsuccess"); } void OnFailure (Object context) { System.out.println ("OnFailure"); } abstract void execute (Object context) throws Exception;}
Callbacktask:
Package Com.cnblogs.yjmyzz.test.callback;public class Callbacktask { private callbackbody body; Public Callbacktask (Callbackbody body) { this.body = body; } protected void Start (final Object context) { final thread t = new Thread (new Runnable () {public void run () { try { Body.execute (context); } catch (Exception e) { e.printstacktrace (); Body.onfailure (context); } Body.onsuccess (context); } }); T.start (); }}
Finally, test a piece:
Callbackapp:
package com.cnblogs.yjmyzz.test.callback;/** * Created by Jimmy on 8/13/15. */ public class Callbackapp {public static void main (string[] args) {System.out.println ("Ready to start performing asynchronous tasks ..."); Final Object context = "contextual information"; New Callbacktask (New Callbackbody () {@Override void execute (Object context) throws Exception { System.out.println ("\ n performing a time-consuming operation ..."); SYSTEM.OUT.PRINTLN (context); Thread.Sleep (5000); System.out.println ("\ n execution done! "); } void Onsuccess (Object context) {System.out.println ("\ n Successful callback function ..."); SYSTEM.OUT.PRINTLN (context); } void OnFailure (Object context) {System.out.println ("\ n failed callback function ..."); SYSTEM.OUT.PRINTLN (context); }}). Start (context); System.out.println ("\ n Async task has started, please wait for completion ..."); }}
Operation Result:
Ready to start executing asynchronous tasks ...
Performing time-consuming operations ...
Contextual information
Asynchronous task has started, please wait to finish ...
Execution Done!
The callback function after success ...
Contextual information
Asynchronous callbacks in Java