java 回调函数

  记得之前做的H5的app,其中消息部分就是使用到了回调机制;还有接入支付宝支付,支付宝的支付结果,也是异步回调的方式返回支付结果信息。但是,这些都是暴露一个接口给支付宝,可能不是很直观。

  直接在java里调用,是怎样呢?写了两个小demo

第一个栗子

需求描述:A和B,A执行一些逻辑,然后A调用B执行另外一些逻辑,然后,在A里执行剩下的逻辑。但是,B执行的逻辑可能很复杂、很耗时,我们不能确定B的完成时间,很显然,我们不可能让线程一直block去等待B的完成,因为这样是极其浪费资源且没什么意义的。所以,有了回调函数的概念。

  1.定义回调的接口

public interface CallInterface {
	public void method();
}

  2.被调用的函数

public class Call implements CallInterface{
	private B b;

	@Override
	public void method() {
		System.out.println("It is call's method");
	}

	public void setB(B b){
		this.b = b;
	}
	
	public void dosomething(){
		System.out.println("Call'class do something ...");
		
		b.method();
	}
}

  3.主动调用函数

public class B implements CallInterface{

	@Override
	public void method() {
		System.out.println("it is b");
	}

	public static void main(String[] args) {
		B b = new B();
		Call a = new Call();
		a.setB(b);
		a.dosomething();
	}
}
  

  第二个栗子

  需求描述:现在有A和B两个线程,A线程循环执行五次逻辑,然后再执行B线程的逻辑。我们一样不能控制A线程的耗时。

1.编写实现Runnable接口的类

public class T implements Runnable{
	private String name;
	public String getName() {
		return name;
	}

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

	private T t;
	
	public void setT(T t){
		this.t = t;
	}
	
	@Override
	public void run() {
		if(null != t){
			for(int i=0 ; i < 5 ; i++){
				System.out.println(Thread.currentThread().getId() + " say hello" + i);
			}
			t.saySomeThing(t.getName());
		}
	}

	public void saySomeThing(String n){
		System.out.println("has done 5 times,and i'm is thread" + this.name+ " ,say to " + n);
		System.out.println("a --> b");
	}
}

2.编写运行入口和实例

public class M {
	public static void main(String[] args) {
		T t1 = new T();
		t1.setName("i'm a");
		Thread th1 = new Thread(t1);
		
		T t2 = new T();
		t2.setName("i'm b");
		Thread th2 = new Thread(t2);
		
		t1.setT(t2);
		
		th1.start();
//		th2.start();
	}
}

如有理解不当地方,说明下,一起学习!






代码下载,请戳我


请参考我,http://hellosure.iteye.com/blog/1130176

请参考我,http://blog.csdn.net/fengyifei11228/article/details/5729445

posted @ 2016-04-13 21:59  Bug开发攻城狮  阅读(117)  评论(0编辑  收藏  举报