多线程-入坑

70 阅读1分钟

两个及以上方法同时运行,达到数倍速度

例如:1个人和面,1个人做臊子,让食客更短的时间吃到臊子面

代码:

public static void main(String[] args) {
    // 创建一个固定大小的线程池
    ExecutorService executor = Executors.newFixedThreadPool(2);

    // 提交任务到线程池执行,并返回 Future 对象
    Future<?> future1 = executor.submit(() -> method1());
    Future<?> future2 = executor.submit(() -> method2());

    // 等待任务执行完成并获取结果(可选)
    try {
        future1.get();
        future2.get();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 关闭线程池
        executor.shutdown();
    }
}
public static void method1() {
    // 这里是方法1的代码
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    System.out.println("Method 1 is running");
}

public static void method2() {
    // 这里是方法2的代码
    System.out.println("Method 2 is running");
}

执行结果

Method 2 is running

Method 1 is running

Process finished with exit code 0

总结

可以看到,Method 2 并没有等Method 1执行完,才开始执行,达到期望值效果