在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;
});
以上是幾種常見的實現異步接口的方式,根據實際需求和情況選擇適合的方式。