Future 模式

本文介绍了Java中利用Future和FutureTask实现异步调用的核心思想,通过示例展示了如何在主函数中不等待耗时操作完成,而是先进行其他任务,最后再获取结果。Future提供了任务取消、检查任务状态以及获取结果等控制功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简述

该模式的核心思想是异步调用。有点类似于异步的 ajax 请求。当调用某方法时,该方法耗时较久,而在主函数中也不急于立刻获取结果。因此可以让调用者立刻返回一个凭证,该方法放到另外线程执行,后续主函数拿凭证再去获取方法的执行结果即可,其结构图如下:

二、通过 FutureTask 实现

注意其中两个耗时操作:
1.如果 doOtherThing 耗时 2s,则整个函数耗时 2s 左右。
2.如果 doOtherThing 耗时0.2s,则整个函数耗时取决于 RealData.costTime,即 1s 左右结束。

public class FutureDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        FutureTask<String> future = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return new RealData().costTime();
            }
        });
        ExecutorService service = Executors.newCachedThreadPool();
        service.submit(future);
        System.out.println("RealData方法调用完毕");
        // 模拟主函数中其他耗时操作
        doOtherThing();
        // 获取RealData方法的结果
        System.out.println(future.get());
    }
    private static void doOtherThing() throws InterruptedException {
        Thread.sleep(2000L);
    }
}
public class RealData {
    public String costTime() {
        try {
            // 模拟RealData耗时操作
            Thread.sleep(1000L);
            return "result";
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "exception";
    }
}

三、通过 Future 实现

与上述 FutureTask 不同的是,RealData 需要实现 Callable 接口。

public class FutureDemo1 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService service = Executors.newCachedThreadPool();
        Future<String> future = service.submit(new RealData1());

        System.out.println("RealData1方法调用完毕");
        // 模拟主函数中其他耗时操作
        doOtherThing();
        // 获取RealData2方法的结果
        System.out.println(future.get());
    }
    private static void doOtherThing() throws InterruptedException {
        Thread.sleep(2000L);
    }
}
public class RealData1 implements Callable {
    public String costTime() {
        try {
            // 模拟RealData耗时操作
            Thread.sleep(1000L);
            return "result";
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "exception";
    }
    @Override
    public String call() throws Exception {
        return costTime();
    }
}

另外 Future 本身还提供了一些额外的简单控制功能,其 API 如下:

    // 取消任务
    boolean cancel(boolean mayInterruptIfRunning);
    // 是否已经取消
    boolean isCancelled();
    // 是否已经完成
    boolean isDone();
    // 取得返回对象
    V get() throws InterruptedException, ExecutionException;
    // 取得返回对象, 并可以设置超时时间
    V get(long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JFS_Study

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值