zoukankan      html  css  js  c++  java
  • Java回调函数

     回调就是调用方持有被调用方的一个引用,而调用方接口的实现类作为被调用方的参数,被调用方返回来调用调用方的方法 
     

    接口CallBack

    public interface CallBack {

    /**回调方法*/
    public void execute(Object ... objects);
    }

    调用方Local

    public class Local implements CallBack ,Runnable{
    private Remote remote;//被调用方作为调用方的一个引用
    private String msg;

    public Local(Remote remote, String msg) {
    super();
    this.remote = remote;
    this.msg = msg;
    }

    @Override
    public void execute(Object... objects) {

    //返回的消息
    System.out.println(objects[0]);

    System.out.println(Thread.currentThread().getName());
    Thread.interrupted();
    }

    public void sendMessage() {
    System.out.println(Thread.currentThread().getName());
    Thread thread = new Thread(this);
    thread.start();
    System.out.println("发送消息");
    }
    public static void main(String[] args)
    {
    Local local = new Local(new Remote(),"Hello");

    local.sendMessage();
    }
    @Override
    public void run() {
    remote.executeMessage(msg, this);
    }

    }

    被调用方Remote

    public class Remote {
    public void executeMessage(String msg,CallBack callBack){

    System.out.println(msg);
    System.out.println("接收到了Local传过来的命令");
    callBack.execute(new String[]{"Hello Local"});
    }
    }

  • 相关阅读:
    端模板引擎
    Orcale Function Sequence
    OData 集成
    validate[.unobtrusive]和Bootstrap实现tooltip错误提示
    Django
    Web Api 控制器
    HelloWorld和数据绑定
    动态Web Api层
    用户管理
    Docker
  • 原文地址:https://www.cnblogs.com/anxue/p/4724628.html
Copyright © 2011-2022 走看看