Java异步Future详解

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

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

简介

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;       // ensure visibility of callable
    }
 public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

当传入构造函数的对象是Runnable时,调用Executors.callable(Runnable,Result)方法返回一个callable的适配器,这个适配器的call方法会调用runnable的run方法,并固定返回传入的result对象。

run方法

在run方法调用callable的call方法,并把返回结果赋值给outcome属性。

public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

get方法

用于获取执行的结果,如果没有执行完则阻塞等待,可以设置超时时间。

 public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

awaitDone方法

在get方法中调用awaitDone方法阻塞等待。awaitDone方法会把当前调用get的线程yield挂起并放在一个链表中,执行完成之后会一一唤醒

private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        WaitNode q = null;
        boolean queued = false;
        for (;;) {
            if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            else if (q == null)
                q = new WaitNode();
            else if (!queued)
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);
            else if (timed) {
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                LockSupport.parkNanos(this, nanos);
            }
            else
                LockSupport.park(this);
        }
    }

finishCompletion执行完成调用

 private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
                for (;;) {
                    Thread t = q.thread;
                    if (t != null) {
                        q.thread = null;
                        LockSupport.unpark(t); // 唤醒线程
                    }
                    WaitNode next = q.next;
                    if (next == null)
                        break;
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }
done();
callable = null;        // to reduce footprint
    }

使用方法

可以直接使用callable或者包装成FutureTask

public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 使用FutureTask
         */
        //      FutureTask<String> futureTask=new FutureTask<String>(new MyTask());
//      ExecutorService myExecuterservice = Executors.newFixedThreadPool(2);
//      myExecuterservice.submit(futureTask);
//      myExecuterservice.shutdown();
//      System.out.println(futureTask.get());

        /**
         * 直接使用callable
         */

        ExecutorService myExecutorService = Executors.newFixedThreadPool(2);
        Future<String> future = myExecutorService.submit(new MyTask());
        System.out.println(future.get());
        myExecutorService.shutdown();


    }
    }

  class MyTask implements Callable<String>{
    public String call(){
        System.out.println("call begins...");
        try {
            Thread.sleep(1000l);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Hello from mytask!";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值