回调函数学习笔记
回调函数是一种思想,不限于哪种语言,回调是什么意思呢,举个栗子,主管分配给你一个任务,你完成任务后需要告知主管你完成了任务,最后这个告知的动作就是回调。
回调又分同步回调和异步回调,写过多线程程序的人大概也都知道同步异步是个怎么回事,不清楚的请看我下面的栗子代码,保证让你秒懂,我比较熟悉的是Java语言,下面给出Java版的简要Demo.
代码
public interface Callback {
void receiveNotification(String string);
}
public class Leader implements Callback {
public void assignTask(Developer student) {
student.doTask(this);
}
public void assignTask(Thread thread) {
thread.start();
}
@Override
public void receiveNotification(String string) {
System.out.println(string);
}
}
public class Developer {
private String name;
void doTask(Callback callback) {
try {
// 假装在认真工作
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
callback.receiveNotification(this.name + " completed the task.");
}
public Developer(String name) {
this.name = name;
}
}
同步回调,主管在得到小明的答复前不能安排小红工作,比如安排小明写代码,安排小红做测试,在小明写好代码前肯定是不能安排小红做测试的,小红表示,代码都还没写好,测个鸡。
public class SyncCallbackTest {
public static void main(String[] args) {
Leader leader = new Leader();
Developer xiaoming = new Developer("xiaoming");
Developer xiaohong = new Developer("xiaohong");
leader.assignTask(xiaoming);
leader.assignTask(xiaohong);
}
}
异步回调,通过线程来实现,主管不需要等待小明的答复再安排小红任务,比如安排小明小红分模块同时进行编码,主管只需要分别安排完任务就不用管了,小明、小红完成任务主动告知主管他们已完成就好,挺像我们主管的,分配完任务就撒手不管了。。。
public class AsyncCallbackTest {
public static void main(String[] args) {
Leader liu = new Leader();
Developer xiaoming = new Developer("xiaoming");
Developer xiaohong = new Developer("xiaohong");
liu.assignTask(new DoJobThread(xiaoming, liu));
liu.assignTask(new DoJobThread(xiaohong, liu));
}
static class DoJobThread extends Thread {
private Developer student;
private Leader teacher;
@Override
public void run() {
student.doTask(teacher);
}
public DoJobThread(Developer student, Leader teacher) {
this.student = student;
this.teacher = teacher;
}
}
}
就这么简单,你理解了吗?^_^