在Java中,可以使用以下几种方法来实现异步调用接口的方法:
public interface AsyncCallback {
void onComplete(Object result);
void onError(Throwable throwable);
}
public class Service {
public void asyncMethod(AsyncCallback callback) {
// 异步执行代码
// 完成后调用 callback.onComplete(result) 或 callback.onError(throwable)
}
}
public class Client {
public void doSomething() {
Service service = new Service();
service.asyncMethod(new AsyncCallback() {
@Override
public void onComplete(Object result) {
// 处理成功结果
}
@Override
public void onError(Throwable throwable) {
// 处理异常情况
}
});
}
}
public class Service {
public CompletableFuture<Object> asyncMethod() {
CompletableFuture<Object> future = new CompletableFuture<>();
// 异步执行代码
// 完成后调用 future.complete(result) 或 future.completeExceptionally(throwable)
return future;
}
}
public class Client {
public void doSomething() {
Service service = new Service();
CompletableFuture<Object> future = service.asyncMethod();
future.thenAccept(result -> {
// 处理成功结果
}).exceptionally(throwable -> {
// 处理异常情况
return null;
});
}
}
public interface Future<T> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
T get() throws InterruptedException, ExecutionException;
T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}
public class Service {
public Future<Object> asyncMethod() {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Object> future = executor.submit(() -> {
// 异步执行代码
// 返回结果或抛出异常
return result;
});
executor.shutdown();
return future;
}
}
public class Client {
public void doSomething() throws ExecutionException, InterruptedException {
Service service = new Service();
Future<Object> future = service.asyncMethod();
// 阻塞等待结果
Object result = future.get();
// 处理结果
}
}
以上是三种常见的实现异步调用接口的方法,具体使用哪种方法取决于具体的业务需求和开发环境。