标签:
场景:A同学向B同学请教问题,B同学需要做方程解答,并需要一定的时间,此时A同学可以先做自己的事情,待B同学完成解答后主动通知A同学答案。
1 public class A { 2 B personB = new B(); 3 public void question(int input1,int input2){ 4 personB.waitAnswer(input1, input2, new CallbackListener() { 5 @Override 6 public void callback(int result) { 7 System.out.println("B 回答:" + result); 8 } 9 }); 10 11 } 12 13 public static void main(String[] args) { 14 A personA = new A(); 15 System.out.println("A向B提问"); 16 personA.question(1,2); 17 System.out.println("在B告诉我答案之前我先做点别的事情"); 18 } 19 }
1 package callback; 2 3 public class B { 4 public void waitAnswer(final int a, final int b, 5 final CallbackListener listener){ 6 new Thread(new Runnable() { 7 @Override 8 public void run() { 9 int c = a + b; 10 listener.callback(c); 11 } 12 }).start(); 13 } 14 }
1 package callback; 2 3 public interface CallbackListener { 4 5 public void callback(int result); 6 7 }
标签:
原文地址:http://www.cnblogs.com/lene-y/p/5689091.html