回调函数

有两个类,A,B,在类A中调用B,在B中调用A的方法完成A的工作,那么这个在B类中调用的A的函数就称为回调函数。

异步回掉函数:类A将自己的工作交给类B后,继续执行剩下的程序,而B继续完成A交给的工作。

 

使用方法:

1、定义一个接口

2、A可以直接继承此接口,也可以定义一个内部类继承此接口;

  定义一个方法,调用B中的方法

3、B中的方法调用A中的方法。

//定义接口
public interface doJob {
    public void fillBlank(int a,int b,int result) throws InterruptedException;
}

//定义A类
public class Student {
    private String name = null;

    public Student(String name){
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
    @SuppressWarnings("unused")
    private int calcAdd(int a,int b){
        return a+b;
    }
    private int useCalculator(int a,int b){
        return new Calculator().add(a,b);
    }
    public void fillBlank(int a,int b){
        int result = useCalculator(a,b);
        System.out.println(name + "使用计算器:" + a + " + " + b + " = " + result);
    }
    public void fillBlank(int result){
        System.out.println(name + "使用计算器: a + b = " + result);
    }
    public class doHomeWork implements doJob{
        public void fillBlank(int a, int b, int result) throws InterruptedException {
            System.out.println(name + "求助小红计算:" +a+" + "+b+" = "+result);
        }
    }
    public void callHelp(final int a,final int b) throws InterruptedException {
        new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(5000);
                    new SuperCalculator().add(a,b,new doHomeWork());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}


//定义B类
public class SuperCalculator {
    public void add(int a,int b,doJob s) throws InterruptedException {
        int result = a +b;
        s.fillBlank(a,b,result);
    }
}

//主函数,测试
public class Test {
    public static void main(String[] args) throws InterruptedException {
        int a =1;
        int b = 2;
        Student s = new Student("小明");
        s.callHelp(a,b);
        System.out.println("结束");
    }
}
View Code

相关文章: