Java回调机制

对Java回调机制进行简单的介绍,并给出简单的示例。

什么是回调

回调,即callback。简单来讲,回调就是A包含B,A的函数Af1调用B的函数Bf1,Bf1又调用A的另一个函数Af2。这个Af2是回调接口中的方法,即A实现了回调接口。那么,Bf1为什么能调用Af2呢,是因为A将自身作为参数传给了Bf1。回调一般用在异步调用中。

举个通俗点的例子:A是Boss,B是worker。Boss让Worker去干活,并且让worker干完活后向Boss报告。Boss分发任务(dispatchWork),让woker去执行(startWork)。worker执行完后调用回调接口的report()函数报告任务完成。

示例

  • CallbackReport.java
public interface CallbackReport {
void report(String msg);
}
  • Boss.java
public class Boss implements CallbackReport{
Worker worker;
public Boss(Worker worker) {
this.worker = worker;
}
public void dispatchWork() {
new Thread(new Runnable() {
@Override
public void run() {
try {
worker.startWork(Boss.this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
@Override
public void report(String msg) {
System.out.println("worker reported: " + msg);
}
}
  • Worker.java
public class Worker {
public void startWork(CallbackReport callback) throws InterruptedException {
System.out.println("worker starts working...");
Thread.sleep(3000);
callback.report("work is done!");
}
}
  • CallbackTest.java
public class CallbackTest {
public static void main(String[] args) throws InterruptedException {
Worker worker = new Worker();
Boss boss = new Boss(worker);
boss.dispatchWork();
System.out.println("dispatched work,wait for done!");
}
}

输出

worker starts working...
dispatched work,wait for done!
worker reported: work is done! //等待3秒后才出现这句
Process finished with exit code 0

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2018 LBD's Blog All Rights Reserved.

访客数 : | 访问量 :