在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();
// 處理結果
}
}
以上是三種常見的實現異步調用接口的方法,具體使用哪種方法取決于具體的業務需求和開發環境。