Future解析与使用

导读

有不少童鞋问我多线程的处理结果要如何返回给调用者呢?今天博主就给大家介绍一下如何采用Future模式,来获取线程的处理结果。 

Future模式

Java 1.5开始,提供了Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果。

Future接口可以构建异步应用,是多线程开发中常见的设计模式。

当我们需要调用一个函数方法时。如果这个函数执行很慢,那么我们就要进行等待。但有时候,我们可能并不急着要结果。

因此,我们可以让被调用者立即返回,让他在后台慢慢处理这个请求。对于调用者来说,则可以先处理一些其他任务,在真正需要数据的场合再去尝试获取需要的数据。

1、Callable与Runnable

java.lang.Runnable是一个接口,在它里面只声明了一个run()方法,run返回值是void,任务执行完毕后无法返回任何结果

public interface Runnable {
    public abstract void run();
}

Callable位于java.util.concurrent包下,它也是一个接口,在它里面也只声明了一个方法叫做call(),这是一个泛型接口,call()函数返回的类型就是传递进来的V类型

public interface Callable<V> {
    V call() throws Exception;
}

2.Future + Callable

Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

怎么使用Future和Callable呢?一般情况下是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载版本

<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);

Future+Callable,使用示例如下(采用第一个方法):

import java.util.Random;
import java.util.concurrent.*;


/**
 * @program: callable
 * @description: Test
 * @author: Mr.Wang
 * @create: 2018-08-12 11:37
 **/
public class MyTest {
    public static void main(String[] args)  {
        ExecutorService executor = Executors.newCachedThreadPool();
        Future<Integer> result = executor.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                return new Random().nextInt();
            }
        });
        executor.shutdown();

        try {
            System.out.println("result:" + result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

结果:

result:297483790

其它方式:

import java.util.Random;
import java.util.concurrent.*;

/**
 * @program: callable
 * @description: testfuture
 * @author: Mr.Wang
 * @create: 2018-08-12 12:11
 **/
public class Testfuture {
    public static void main(String[] args){
        //第一种方式
        FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return new Random().nextInt();
            }
        });
        new Thread(task).start();
        //第二种方方式
//        ExecutorService executor = Executors.newSingleThreadExecutor();
//        FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
//            @Override
//            public Integer call() throws Exception {
//                return new Random().nextInt();
//            }
//        });
//        executor.submit(task);

        try {
            System.out.println("result: "+task.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

结果:

result:-358490809

3、Future 接口的局限性

了解了Future的使用,这里就要谈谈Future的局限性。Future很难直接表述多个Future 结果之间的依赖性,开发中,我们经常需要达成以下目的:

  • 将两个异步计算合并为一个(这两个异步计算之间相互独立,同时第二个又依赖于第一个的结果)
  • 等待 Future 集合中的所有任务都完成。
  • 仅等待 Future 集合中最快结束的任务完成,并返回它的结果。

总结

因为Future本身有一些局限性,所以还是不能满足大部分应用场景,下一节我将给大家介绍更高级的用法:CompletableFuture。

要更多干货、技术猛料的孩子,快点拿起手机扫码关注我,我在这里等你哦~

                                                       

`std::future` 是 C++11 引入的并发编程工具,用于异步操作的结果访问。它提供了一种机制来获取异步任务(如 `std::async`、`std::packaged_task` 或 `std::promise`)的返回值或异常。以下是关键点解析: --- ### 核心特性 1. **获取异步结果** 通过 `get()` 方法阻塞当前线程,直到异步任务完成并返回结果(或抛出异常)。 ```cpp std::future<int> fut = std::async([](){ return 42; }); int result = fut.get(); // 阻塞直到结果就绪 ``` 2. **状态检查** - `valid()`:检查 `future` 是否关联共享状态(如未调用 `get()` 或 `wait()`)。 - `wait()`:阻塞等待结果就绪,不获取值。 - `wait_for()`/`wait_until()`:超时或定时等待。 3. **异常传递** 异步任务中的异常会通过 `future` 重新抛出(在调用 `get()` 时)。 --- ### 典型用法 #### 1. 结合 `std::async` ```cpp auto fut = std::async(std::launch::async, [](){ return std::string("Hello, Future!"); }); std::cout << fut.get(); // 输出结果 ``` #### 2. 结合 `std::promise` 和 `std::thread` ```cpp std::promise<int> prom; std::future<int> fut = prom.get_future(); std::thread([&prom] { prom.set_value(100); // 在子线程中设置值 }).detach(); std::cout << fut.get(); // 输出 100 ``` --- ### 注意事项 1. **一次性访问** `get()` 只能调用一次,调用后 `future` 变为无效(除非是 `std::shared_future`)。 2. **线程安全** `future` 本身不是线程安全的,通常由一个线程等待结果。 3. **性能开销** 异步操作可能涉及线程创建或上下文切换,需权衡任务复杂度。 --- ### 示例代码 ```cpp #include <iostream> #include <future> #include <thread> int main() { // 使用 std::async auto fut1 = std::async([](){ return 1 + 1; }); std::cout << "Async result: " << fut1.get() << std::endl; // 使用 std::promise std::promise<std::string> prom; auto fut2 = prom.get_future(); std::thread([&prom] { prom.set_value("Thread completed"); }).join(); std::cout << fut2.get() << std::endl; return 0; } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值