当你需要同时执行两个线程,每个线程执行不同的方法时,可以使用Java的多线程编程。下面是一个简单的示例,演示如何使用Java 8的CompletableFuture
实现并发执行不同的方法:
import java.util.concurrent.CompletableFuture;
public class ConcurrentMethodExecution {
public static void main(String[] args) {
// 同时执行两个方法
CompletableFuture<String> result1 = CompletableFuture.supplyAsync(() -> method1());
CompletableFuture<String> result2 = CompletableFuture.supplyAsync(() -> method2());
// 等待两个方法执行完成
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(result1, result2);
// 处理两个方法执行完成后的结果
combinedFuture.thenRun(() -> {
try {
String result1Value = result1.get();
String result2Value = result2.get();
// 在这里处理结果
System.out.println("Result from method1: " + result1Value);
System.out.println("Result from method2: " + result2Value);
} catch (Exception e) {
e.printStackTrace();
}
});
// 防止主线程提前退出
try {
Thread.sleep(5000); // 等待异步操作完成
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 第一个方法
private static String method1() {
// 模拟长时间运行的方法
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Result from method1";
}
// 第二个方法
private static String method2() {
// 模拟长时间运行的方法
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Result from method2";
}
}
在这个例子中,method1
和 method2
分别模拟两个不同的方法。使用 CompletableFuture.supplyAsync
来异步执行这两个方法。CompletableFuture.allOf
用于等待两个异步方法的完成。在 thenRun
部分,你可以处理两个方法执行完成后的结果。请注意,最后的 Thread.sleep(5000)
是为了让异步操作有足够的时间完成,否则主线程可能会提前退出。在实际的应用程序中,你不太可能需要这样的等待。