Java中實現異步調用的方法有以下幾種:
Thread thread = new Thread(new Runnable() {
public void run() {
// 異步任務代碼
}
});
thread.start();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Callable<String>() {
public String call() throws Exception {
// 異步任務代碼
return "異步任務執行結果";
}
});
// 獲取異步任務的執行結果
String result = future.get();
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 異步任務代碼
return "異步任務執行結果";
});
future.thenAccept(result -> {
// 處理異步任務的執行結果
});
public interface AsyncCallback {
void onSuccess(String result);
void onFailure(Throwable throwable);
}
public class AsyncClass {
public void asyncMethod(AsyncCallback callback) {
// 異步任務代碼
String result = "異步任務執行結果";
callback.onSuccess(result);
}
}
public class MainClass {
public static void main(String[] args) {
AsyncClass asyncObj = new AsyncClass();
asyncObj.asyncMethod(new AsyncCallback() {
public void onSuccess(String result) {
// 處理異步任務的執行結果
}
public void onFailure(Throwable throwable) {
// 處理異步任務的異常情況
}
});
}
}
以上是一些常見的實現異步調用的方法,根據具體的需求和場景選擇合適的方法。