在Java中,可以使用回调、Future和CompletableFuture等方式来实现异步接口。
public interface AsyncCallback {
void onSuccess(Object result);
void onFailure(Exception e);
}
public interface AsyncService {
void doSomethingAsync(AsyncCallback callback);
}
public class AsyncServiceImpl implements AsyncService {
@Override
public void doSomethingAsync(AsyncCallback callback) {
// 异步操作
// 执行完毕后调用回调方法
if (success) {
callback.onSuccess(result);
} else {
callback.onFailure(exception);
}
}
}
// 使用
AsyncService asyncService = new AsyncServiceImpl();
asyncService.doSomethingAsync(new AsyncCallback() {
@Override
public void onSuccess(Object result) {
// 处理成功结果
}
@Override
public void onFailure(Exception e) {
// 处理异常情况
}
});
public interface AsyncService {
Future<Object> doSomethingAsync();
}
public class AsyncServiceImpl implements AsyncService {
@Override
public Future<Object> doSomethingAsync() {
ExecutorService executor = Executors.newFixedThreadPool(1);
return executor.submit(() -> {
// 异步操作
return result;
});
}
}
// 使用
AsyncService asyncService = new AsyncServiceImpl();
Future<Object> future = asyncService.doSomethingAsync();
while (!future.isDone()) {
// 等待操作完成
}
try {
Object result = future.get();
// 处理结果
} catch (InterruptedException | ExecutionException e) {
// 处理异常情况
}
public interface AsyncService {
CompletableFuture<Object> doSomethingAsync();
}
public class AsyncServiceImpl implements AsyncService {
@Override
public CompletableFuture<Object> doSomethingAsync() {
CompletableFuture<Object> future = new CompletableFuture<>();
// 异步操作
// 执行完毕后设置结果或异常
if (success) {
future.complete(result);
} else {
future.completeExceptionally(exception);
}
return future;
}
}
// 使用
AsyncService asyncService = new AsyncServiceImpl();
asyncService.doSomethingAsync().thenAccept(result -> {
// 处理成功结果
}).exceptionally(e -> {
// 处理异常情况
return null;
});
以上是几种常见的实现异步接口的方式,根据实际需求和情况选择适合的方式。