Java中实现异步调用的方法有以下几种:
Thread thread = new Thread(new Runnable() {
public void run() {
// 异步任务代码
}
});
thread.start();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Callable<String>() {
public String call() throws Exception {
// 异步任务代码
return "异步任务执行结果";
}
});
// 获取异步任务的执行结果
String result = future.get();
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 异步任务代码
return "异步任务执行结果";
});
future.thenAccept(result -> {
// 处理异步任务的执行结果
});
public interface AsyncCallback {
void onSuccess(String result);
void onFailure(Throwable throwable);
}
public class AsyncClass {
public void asyncMethod(AsyncCallback callback) {
// 异步任务代码
String result = "异步任务执行结果";
callback.onSuccess(result);
}
}
public class MainClass {
public static void main(String[] args) {
AsyncClass asyncObj = new AsyncClass();
asyncObj.asyncMethod(new AsyncCallback() {
public void onSuccess(String result) {
// 处理异步任务的执行结果
}
public void onFailure(Throwable throwable) {
// 处理异步任务的异常情况
}
});
}
}
以上是一些常见的实现异步调用的方法,根据具体的需求和场景选择合适的方法。