java回调机制

(与代码无直接关系)原来用到的不多,现在发现这个东西在android请求服务器时贼好用
一个请求工具类,请求用线程发起,返回信息时通过回调函数将数据返回给activity
写法记录:

public interface CallBackInterface {
    void callBack(String str);
}
/** 类似activity */
public class Print implements CallBackInterface {
    public Print(){
        new TestThread(this);
        System.out.println("我写在调用线程后面");
    }
    /** 实现接口 */
    public  void callBack(String str){
        System.out.println(str);
    }
}
/** 类似请求类 */
public  class TestThread {
    public TestThread(CallBackInterface cbi){
        Thread thread = new Thread(){
            @Override
            public void run(){
                try {
                    sleep(2000);
                    String str = "hello, 线程快跑完了";
                    cbi.callBack(str);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
    }
}
public class Main{
    public static void main(String[] args) {
        new Print();
    }
}

java回调机制_第1张图片

你可能感兴趣的:(java,设计)