Java实现简单的回调

主函数

public class Test {
    public static void main(String[] args) {
        Deal deal=new Deal(15, new Result() {
            @Override
            public void msg(String re) { //接口拿到处理结果
                System.out.println(re);
            }
        });
        //开始处理
        deal.judge();
    }
}

回调消息接口

public interface Result {
    void msg(String re);
}

后台处理函数

public class Deal {
    Result re;
    int data;
    public Deal(int data,Result re) {
        this.re = re;
        this.data=data;

    }
    public void judge(){

        for (int i = 0; i < data; i++) {
            System.out.println(i);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //将结果传给接口
        if(data>10){
            re.msg("Failure!"); 
        }else{
            re.msg("Success!");
        }
    }
}

你可能感兴趣的:(Java)