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

  • 相关阅读:
    python 类
    hdu 5761 Rowe Bo 微分方程
    calendar 示例
    hdu 5753 Permutation Bo
    hdu 5752 Sqrt Bo
    finally 语句
    throws 和 throw
    python打开.pkl的文件并显示里面的内容
    Python 类变量,成员变量,静态变量,局部变量
    python 实例方法,类方法,静态方法,普通函数
  • 原文地址:https://www.cnblogs.com/anxue/p/4724628.html
Copyright © 2011-2022 走看看