`
vvggsky
  • 浏览: 65441 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

消息的发送与回调

    博客分类:
  • J2SE
阅读更多
/**  
 * 回调接口  
 * @author KOOK  
 *  
 */  
public interface CallBack {   
    /**  
     * 执行回调方法  
     * @param objects   将处理后的结果作为参数返回给回调方法  
     */  
    public void execute(Object... objects );   
}  



/**  
 * 简单本地发送异步消息的类  
 * @author KOOK  
 *  
 */  
public class Local implements CallBack,Runnable{   
       
    /**  
     * 远程接收消息的类,模拟point-to-point  
     */  
    private Remote remote;   
       
    /**  
     * 发送出去的消息  
     */  
    private String message;   
       
    public Local(Remote remote, String message) {   
        super();   
        this.remote = remote;   
        this.message = message;   
    }   
  
    /**  
     * 发送消息  
     */  
    public void sendMessage()   
    {   
        /**当前线程的名称**/  
        System.out.println(Thread.currentThread().getName());   
        /**创建一个新的线程发送消息**/  
        Thread thread = new Thread(this);   
        thread.start();   
        /**当前线程继续执行**/  
        System.out.println("Message has been sent by Local~!");   
    }   
  
    /**  
     * 发送消息后的回调函数  
     */  
    public void execute(Object... objects ) {   
        /**打印返回的消息**/  
        System.out.println(objects[0]);   
        /**打印发送消息的线程名称**/  
        System.out.println(Thread.currentThread().getName());   
        /**中断发送消息的线程**/  
        Thread.interrupted();   
    }   
       
    public static void main(String[] args)   
    {   
        Local local = new Local(new Remote(),"Hello");   
           
        local.sendMessage();   
    }   
  
    public void run() {   
        remote.executeMessage(message, this);   
           
    }   
}  


/**  
 * 处理消息的远程类  
 * @author KOOK  
 *  
 */  
public class Remote {   
  
    /**  
     * 处理消息  
     * @param msg   接收的消息  
     * @param callBack  回调函数处理类  
     */  
    public void executeMessage(String msg,CallBack callBack)   
    {   
        /**模拟远程类正在处理其他事情,可能需要花费许多时间**/  
        for(int i=0;i<1000000000;i++)   
        {   
               
        }   
        /**处理完其他事情,现在来处理消息**/  
        System.out.println(msg);   
        System.out.println("I hava executed the message by Local");   
        /**执行回调**/  
        callBack.execute(new String[]{"Nice to meet you~!"});   
    }   
       
}  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics