JAVA异步加回调的例子

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!"});    
    }

}

 

转载于:https://www.cnblogs.com/onlysun/p/4520668.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值