参考这篇博客http://www.importnew.com/24220.html
例子中老师类实现Callback接口,里面拿到一个学生实例(真实场景中可以拿到学生类的集合,挨个提问)实例化一个老师,提出一个问题。有个学生类,实例化一个具体的学生,回答这个问题,学生回答问题的时候需要把老师这个类当做参数传进去,线程睡3s,模拟学生思考问题,学生给出答案,因为已经拿到老师类了,可以回调老师类中的老师反馈方法,判断学生回答的是否正确。
上面博客中实现了同步,我改造下实现了异步,实现方式是开一个新线程,lambda表达式书写。
代码如下:
回调接口,学生回答完毕,老师给出结果
package 回调.Java团长代码实例;
/**
* Created by Administrator on 2018/6/29 0029.
* https://mp.weixin.qq.com/s/gt75lgeMm95YtbhU-stGLg
*/
public interface Callback {
void tellAnswer(int answer);
}
Teacher类,实现Callback接口
package 回调.Java团长代码实例;
/**
* Created by Administrator on 2018/6/29 0029.
*/
public class Teacher implements Callback{
private Student student;
public Teacher (Student student) {
this.student = student;
}
public void askQuestion() {
//student.resolveQuestion(this); //此处是同步回调。
new Thread(()-> student.resolveQuestion(this)).start(); //这里实现了异步,此处的this也可以用Teacher.this代替,
// 如果不用lambda表达式,用匿名内部类创建new Runnable()则一定要用Teacher.this
}
@Override
public void tellAnswer(int answer) {
System.out.println("你的答案是:" + answer + "正确");
}
}
学生接口,有回答问题方法
package 回调.Java团长代码实例;
/**
* Created by Administrator on 2018/6/29 0029.
*/
public interface Student {
public void resolveQuestion(Callback callback);
}
一个名叫Ricky的同学解决老师提出的问题
package 回调.Java团长代码实例;
/**
* Created by Administrator on 2018/6/29 0029.
* 一个名叫Ricky的同学解决老师提出的问题
*/
public class Ricky implements Student {
@Override
public void resolveQuestion(Callback callback) {
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
//回调,告诉老师问题的答案
callback.tellAnswer(3);
}
}
测试
package 回调.Java团长代码实例;
import org.junit.Test;
/**
* Created by Administrator on 2018/6/29 0029.
*/
public class CallbackTest {
@Test
public void testCallback() {
Student student = new Ricky();
Teacher teacher = new Teacher(student);
teacher.askQuestion();
System.out.println("end");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}