Java的Future模式(基于JDK1.8)

1 概述

在我们使用多线程的时候,如果我们需要在主线程中拿到其余线程执行输出的内容,同时在子线程运行的时候,我们主线程依然运行,只是在合适的时候来拿子线程的结果就行了,这个时候我们怎么办呢?这就需要用到Future模式了。下面我们直接上一个列子来直观地演示Future模式。

2 实例

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author: LIUTAO
 * @Date: Created in 2019/2/22  10:29
 * @Modified By:
 */
public class FutureDemo {
    public static void main(String[] args) {
        Callable<String> callable = () -> {

            //模拟烹饪食物的时间5秒
            Thread.sleep(5000);
            return "food is ok";
        };

        FutureTask<String> futureTask = new FutureTask(callable);
        new Thread(futureTask).start();
        System.out.println("begin to make cafe");
        try {

            //模拟煮咖啡的时间3秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("cafe is ok");
        if(!futureTask.isDone()){
            try {
                System.out.println("food is not ok , wait 3000 seconds");
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            String result = futureTask.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}

运行上面的例子,如果我们再加入时间统计的代码,我们可以看见整个过程消耗的时间远远小于煮咖啡和烹饪食物的事件总和,并且最终我们也拿到了烹饪的结果。接下来我们来分析一下Future模式的源码。

3 源码分析

(1)Callable接口

直接上源码来看一下Callable接口的具体代码。

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

Callable接口就只有一个call()函数,这个接口其实相当于Runnable接口的一个补充,这个接口的唯一函数改善了Runnable接口的唯一函数没有返回值和无法处理异常的不足。

(2)FutureTask

FutureTask类其实是对Callable接口的进一步包装,并且对外提供了很多操作函数,以此来获取到线程的执行结果和执行的状态。

我们首先还是来看一看FutureTask的继承结构。

从上图可以看出这个接口实现了RunnableFuture接口,其实RunnableFuture接口什么也没有做,仅仅将Runnable和Future接口进行了合并。这里Future接口就规定了FutureTask类的主要函数。

get方法:获取计算结果(如果还没计算完,也是必须等待的)
cancel方法:还没计算完,可以取消计算过程
isDone方法:判断是否计算完
isCancelled方法:判断计算是否被取消

针对FutureTask的函数分析,我们就仅仅分析下run()和get()函数,其余的函数都比较简单,大家可以自己看源码。

A. run函数

public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {

            //获取Callable对象(由构造函数传入)
            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);
        }
    }

可以看出上面的逻辑还是非常简单,将执行结果进行保存就行了。这里涉及到一个state属性,其实这个属性就是对线程执行的状态进行保存的,我们来看一看有哪些值。

    /**
     * 任务的运行状态,初始时为NEW。
     * 
     * 可能的状态转换:
     * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * NEW -> INTERRUPTING -> INTERRUPTED
     */
    private volatile int 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;

B. get函数

通过get函数我们可以获取Callable任务的执行结果,这里我们来看一看get函数的具体逻辑。

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

当state的状态为NEW或者COMPLETING的时候将调用awaitDone函数,awaitDone函数根据传入的参数来决定是否涉及到线程阻塞。

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

            //如果线程已经中断,移除等待节点(这里的等待节点就是由调用get的线程组成)
            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)
                //初始化当前节点,从这可以看出调用get的所有线程将会组成一个由WaitNode组成的单向链表
                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);
        }
    }

awaitDone函数的作用其实就是在Callable任务没有执行完成前进行阻塞等待。那么什么时候会唤醒当代线程呢?这里就是我们前面提到的set函数。

protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); 

            //处理完成状态
            finishCompletion();
        }
    }

这里的唤醒等待任务的操作其实是在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
    }

上面就是对Future模式的学习,欢迎交流和指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值