Skip to content

Callback

Chen Xiaojie edited this page Dec 18, 2022 · 1 revision

字典解释,Callback 有若干个意思:

  • 回拨:Callers often forget to leave contact information for a callback. 打电话的人总是忘记留下用于回拨联系方式
  • 复岗、再雇佣:The company has not committed to how many workers will return, but the callbacks will continue in phases. 虽然公司没有尽力让工人回来,但是正在阶段性地使工人复岗。

显然,在计算机,Callback 更倾向于 回拨 的意思。中文界习惯称之为 回调。在 wiki 里,回调 又叫 call-after,也就是延迟执行代码,通常是将 数据可执行代码 传输到其他代码里,并让其运行,运行后获取结果。

根据 等待结果 与否,Callback 函数可分为两种 synchronous callbackasynchronous callback

同步回调 Synchronous callback

// 函数
Class Customer{
    public boolean hasOverHundredPoints() {
        return this.points > 100;
    }
}

List<Customer> customersWithMoreThan100Points = customers
  .stream()
  .filter(Customer::hasOverHundredPoints)
  .collect(Collectors.toList());

将自定义函数 hasOverHundredPoints 传输给 stream,并由 stream 执行,该行为就是 callback。而 stream 必须等待 filter() 的处理结果,才能执行下一步 collect() ,该等待即同步。

异步回调 Asynchronous callback

// 函数
class Task implements Callable<String> {
    public String call() throws Exception {
        return longTimeCalculation(); 
    }
}

// 回调
ExecutorService executor = Executors.newFixedThreadPool(4); 
Callable<String> task = new Task();// 定义任务:
Future<String> future = executor.submit(task);// 提交任务并获得Future:

// 从Future获取异步执行返回的结果:
String result = future.get(); // 可能阻塞

上述示例参考 此处

Clone this wiki locally