package com.sunchao.callback; /** * callback interface * @author Administrator * */ public interface CallBack { /** * execute the callback method * @param objects make the asyn execute result as the parameter of callback method */ public void execute(Object... objects ); }
package com.sunchao.callback; /** * Local class which use to send the message * to the remote class * @author Administrator * */ public class Local implements CallBack,Runnable { private Remote remote; private String message; public Local(String message, Remote remote){ super(); this.remote = remote; this.message = message; } @Override public void run() { this.remote.executeMessage(message, this); } /** * this method is used by the handler class * to callback */ @Override public void execute(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 void sendMessage(){ System.out.println(Thread.currentThread().getName()); Thread newThread = new Thread(this); newThread.start(); System.out.println("The message has been send!"); } public static void main(String args[]){ Local local = new Local("hello", new Remote()); local.sendMessage(); } }
package com.sunchao.callback; /** * the remote class which used by to handle * the message which send from the local class * @author Administrator * */ public class Remote { /** * the method used to handle the message * @param msg the message send from the callback class * @param callBack the callback class */ public void executeMessage(String msg, CallBack callBack){ /** * the empty loop represent the remote class is busying to * handler the message */ for(int i = 0; i < 10000; i++){ } System.out.println("oh my god ,i have done the message from the local : " + msg); /** * the remote handler has done the message,and now * to notify the local class */ callBack.execute((Object[])new String[]{"nice to see again!"}); } }