面试题答案
一键面试在Java异步编程中,使用回调机制处理异步任务结果的步骤如下:
- 定义回调接口,该接口包含处理异步任务结果的方法。
- 在异步任务执行的类中,接收回调接口的实例作为参数,并在任务完成时调用回调方法。
以下是代码示例:
// 定义回调接口
interface ResultCallback {
void onResult(int result);
}
// 模拟异步任务类
class AsyncTask {
public void executeAsync(ResultCallback callback) {
new Thread(() -> {
// 模拟任务执行耗时
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int result = performCalculation();
callback.onResult(result);
}).start();
}
private int performCalculation() {
return 42; // 模拟计算结果
}
}
public class Main {
public static void main(String[] args) {
AsyncTask asyncTask = new AsyncTask();
asyncTask.executeAsync(result -> {
System.out.println("异步任务结果: " + result);
});
System.out.println("主线程继续执行其他任务...");
}
}
在上述代码中:
ResultCallback
接口定义了onResult
方法,用于处理异步任务的结果。AsyncTask
类的executeAsync
方法接收ResultCallback
实例作为参数,并在新线程中执行异步任务。任务完成后,调用callback.onResult(result)
将结果传递给回调方法。- 在
Main
类中,创建AsyncTask
实例并调用executeAsync
方法,传入一个实现了ResultCallback
接口的匿名类实例,在其onResult
方法中处理异步任务的结果。同时,主线程继续执行其他任务。