消息的发送与回调


/**
* 回调接口
* @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~!"});
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值