Java异步Future详解

Java的Future接口用于处理有返回值的异步任务,其核心实现FutureTask结合了Runnable和Future接口。文章详细介绍了FutureTask的内部属性如状态(state)、构造函数、run方法、get方法以及awaitDone方法的工作原理,展示了如何使用FutureTask进行异步操作。
摘要由CSDN通过智能技术生成

简介

Future主要用于有返回值的异步任务。最核心的类是FutureTask,它是Future接口唯一的实现类。

FutureTask

这里写图片描述
可以看出FutureTask类实现了Runnable和Future接口。
内部属性有

    private volatile int state;
    private Callable<V> callable;
    /** The result to return or exception to throw from get() */
    private Object outcome; // non-volatile, protected by state reads/writes
    /** The thread running the callable; CASed during run() */
    private volatile Thread runner;
    /** Treiber stack of waiting threads */
    private volatile WaitNode waiters;

其中

  • state表示任务执行状态,有下面几个取值
    private static final int NEW = 0;
    private static final int COMPLETING = 1;
    private static final int NORMAL = 2;
    private static final int EXCEPTIONAL = 3;
    private static final int CANCELLED = 4;
    private static final int INTERRUPTING = 5;
    private static final int INTERRUPTED = 6;
  • callable是实际要执行的run方法的对象
  • outCome是执行的结果
  • runner是执行run方法的线程
  • waitNodes是一个链表,存储调用get或者别的方法而阻塞的线程

构造函数

有两周构造函数,分别传入Runnable对象和Callable对象

 public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值