Javaで複数のインターフェースを並行に呼び出す方法
Java のマルチスレッド技術を使用すれば、複数の API を並列に呼び出すことが可能です。複数のスレッドを作成することで、それぞれが別の API を呼び出し、並列に実行できます。
以下に簡単なサンプルコードを示します。
import java.util.concurrent.*;
public class ParallelInterfaceInvocation {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
// 创建多个Callable任务,每个任务分别调用一个接口
Callable<String> task1 = new Callable<String>() {
@Override
public String call() throws Exception {
// 调用接口1的逻辑
return "Result from Interface 1";
}
};
Callable<String> task2 = new Callable<String>() {
@Override
public String call() throws Exception {
// 调用接口2的逻辑
return "Result from Interface 2";
}
};
// 提交任务给线程池
Future<String> future1 = executor.submit(task1);
Future<String> future2 = executor.submit(task2);
try {
// 获取接口调用结果
String result1 = future1.get();
String result2 = future2.get();
// 处理接口调用结果
System.out.println("Result from Interface 1: " + result1);
System.out.println("Result from Interface 2: " + result2);
// 关闭线程池
executor.shutdown();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
上記コードでは、スレッドプールを固定サイズ 2 で作成し、2つの異なるインターフェイス呼び出しのロジックを表す 2 つの Callable タスクを作成しました。その後、これらのタスクをスレッドプールに送信し、各タスクの実行結果を表す 2 つの Future オブジェクトを取得しました。Future オブジェクトの get() メソッドを呼び出すことで、各タスクの戻り値を取得し、適切な処理を実行できます。
これにより、複数のインターフェイスを非同期で呼び出すことができます。インターフェイスの呼び出しがブロッキングである場合は、Futureオブジェクトのget()メソッドを使用してインターフェイスの呼び出しが完了するのを待ちます。インターフェイスの呼び出しが非ブロッキングである場合は、FutureオブジェクトのisDone()メソッドを使用してインターフェイスの呼び出しが完了したかどうかを判断できます。