java的回调
1,明确什么是回调方法
2,采用接口来实现回调
java同步回调
一个类实现了接口,将他传递给另一个类,在另一个类调用接口中方法
public class Bar implements Foo.FooCallback { public void eatFood() { System.out.println("in eatFood() "); } //这是回调方法 @Override public void eat(String food) { System.out.println("【@】" + food); } }
public class Foo{ public FooCallback fooCallback; public Foo(FooCallback fooCallback) { this.fooCallback = fooCallback; } public interface FooCallback{ public void eat(String food); } public void say() { fooCallback.eat("西安蛋炒饭"); } }
public class demo { public static void main(String args[]) { Bar bar = new Bar(); Foo foo = new Foo(bar); foo.say(); } }
java异步回调
其实和同步回调差不多,只是新开线程,然后在新线程中回调接口中的方法
public interface EatRice { public void eat(String food); }
public class XiaoMing implements EatRice { public void say() { } @Override public void eat(String food) { System.out.print("小明和小李一起去吃" + food); } }
public class XiaoLi {// 小李 protected EatRice er; public void setEatRiceListener(EatRice er, String food) { this.er = er; washFace(food); } public void washFace(String food) { System.out.print("小李要洗漱"); new Thread(new Runnable() { @Override public void run() { try { // 小李洗漱的同时小明玩手机,开启线程实现异步 play(); Thread.sleep(10000); System.out.print("10秒后 "); // B调用A的方法 er.eat(food); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } public void play() { System.out.println(" 小明要玩手机"); } }
public static void main(String[] args) { EatRice er = new XiaoMing(); new XiaoLi().setEatRiceListener(er, "小龙虾"); }