回调函数

回调函数的概念

正常软件模块之间总是存在调用接口,从调用方式上可以将他们分成三类:同步调用,回调和异步调用。同步调用是一种阻塞式调用,它是一种单向调用,调用方要等到对方执行完毕才能返回。异步调用是一种类似消息或事件的机制,不过它的调用方法刚好相反,接口的服务在收到某种消息或发生某种事件时会主动通知客户方(调用的客户方的接口)。回调是一种双向调用模式,被调用方在接口被调用时也会调用也会调用对方的接口。


简单的说,你打电话问你妈妈饭做好了吗?这是同步调用;你妈妈给你打电话叫你回家吃饭,这是异步调用;你打电话告你你妈妈,饭好了给我打电话叫我回去吃饭,这是回调。

回调函数流程

1.声明一个接口CallBack;

2.Class A中实现该接口;

3.Class A中声明一个Class B的引用;

4.Class B中有一个参数为CallBack的方法b;

5.A的对象a调用B的方法b;

6.B就可以在b中调用A的方法了。

声明接口

public interface CallBack {
	public void lunchIsReady();
}

在Class A中实现该接口,A中声明Class B的引用,调用参数为CallBack的方法

public class Me implements CallBack {
	public Me(MyMother mother){
		this.mother = mother;
	}
	private MyMother mother;
	public void lunchReadyOrNot(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mother.phonecall(Me.this);
			}
		}) .start();
		waiting();
	}
	public void waiting(){
		System.out.println("waiting phonecall");
	}
	@Override
	public void lunchIsReady() {
		// TODO Auto-generated method stub
		System.out.println("I will go home and have lunch now");
	}

}
Class B中参数为CallBack的方法

public class MyMother {
	public void phonecall(CallBack callback){
		System.out.println("孩子询问我午饭是否做好");
		System.out.println("午饭正在进行中...");
		for(int i=0;i<1000;i++){}
		callback.lunchIsReady();
	}
}

主函数
public class Test {
	public static void main(String []args){
		MyMother mother = new MyMother();
		Me me = new Me(mother);
		me.lunchReadyOrNot();
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值