在Java中,可以使用以下幾種方法來實現(xiàn)接口的異步調(diào)用:
示例代碼:
public interface Callback {
void onComplete(String result);
}
public class AsyncService {
public void doSomethingAsync(Callback callback) {
// 異步操作
// 操作完成后調(diào)用回調(diào)方法
callback.onComplete("操作完成");
}
}
public class Main {
public static void main(String[] args) {
AsyncService asyncService = new AsyncService();
asyncService.doSomethingAsync(new Callback() {
@Override
public void onComplete(String result) {
System.out.println(result);
}
});
}
}
示例代碼:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class AsyncService {
public Future<String> doSomethingAsync() {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
// 異步操作
return "操作完成";
}
};
return executor.submit(callable);
}
}
public class Main {
public static void main(String[] args) {
AsyncService asyncService = new AsyncService();
Future<String> future = asyncService.doSomethingAsync();
try {
String result = future.get();
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
這樣可以通過調(diào)用Future的get方法來等待異步操作完成,并獲取結(jié)果。
示例代碼:
import java.util.concurrent.CompletableFuture;
public class AsyncService {
public CompletableFuture<String> doSomethingAsync() {
return CompletableFuture.supplyAsync(() -> {
// 異步操作
return "操作完成";
});
}
}
public class Main {
public static void main(String[] args) {
AsyncService asyncService = new AsyncService();
asyncService.doSomethingAsync().thenAccept(result -> {
System.out.println(result);
}).join();
}
}
這樣可以通過使用CompletableFuture的方法鏈來執(zhí)行異步操作和處理操作結(jié)果。