用java8 要同时执行两个线程,每个线程里执行不同方法,可以使用Java的多线程编程。

当你需要同时执行两个线程,每个线程执行不同的方法时,可以使用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";
    }
}

在这个例子中,method1method2 分别模拟两个不同的方法。使用 CompletableFuture.supplyAsync 来异步执行这两个方法。CompletableFuture.allOf 用于等待两个异步方法的完成。在 thenRun 部分,你可以处理两个方法执行完成后的结果。请注意,最后的 Thread.sleep(5000) 是为了让异步操作有足够的时间完成,否则主线程可能会提前退出。在实际的应用程序中,你不太可能需要这样的等待。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值