Package Com.sunchao.callback; /** @author*/Publicinterface CallBack {/** * Execute the callback method @param objects make the Asyn execute Result as the parameter of callback method */public void Execute (Object ... objects);}
PackageCom.sunchao.callback;/*** Local class which use to send the message * to the remote class *@authorAdministrator **/ Public classLocalImplementscallback,runnable {Privateremote remote; PrivateString message; PublicLocal (String message, remote remote) {Super(); This. Remote =remote; This. Message =message; } @Override Public voidrun () { This. Remote.executemessage (Message, This); } /*** This method was used by the handler class * to callback*/@Override Public voidExecute (Object ... objects) {/*** Print the result of handler class * and send to the local*/System.out.println (objects[0]); System.out.println (Thread.CurrentThread (). GetName ()); }/*** New A thread to handle the message;*/ Public voidSendMessage () {System.out.println (Thread.CurrentThread (). GetName ()); Thread Newthread=NewThread ( This); Newthread.start (); System.out.println ("The message has been send!"); } Public Static voidMain (String args[]) {Local local=NewLocal ("Hello",NewRemote ()); Local.sendmessage (); }}
PackageCom.sunchao.callback;/*** The remote class which used by to handle * The message which send from the local class *@authorAdministrator **/ Public classRemote {/*** The method used to handle the message *@paramMSG The message send from the callback class *@paramCallBack the CallBack class*/ Public voidexecutemessage (String msg, CallBack CallBack) {/*** The empty loop represent the remote class is busying to * handler the message*/ for(inti = 0; I < 10000; i++) {} System.out.println ("Oh my God, I have the do the message from the Local:" +msg); /*** The remote handler have done the Message,and now * to notify the local class*/Callback.execute ((object[])Newstring[]{"Nice to see again!"}); }}
Examples of Java asynchronous plus callbacks