Callable 和 FutureTask 带返回值线程使用和源码分析

Callable 和 FutureTask 可以创建带返回值的线程,那它是怎么实现的呢?笔者下面分析,先看看它是怎么使用的

1、Callable FutureTask使用

新建 Name类,实现 Callable 接口,返回 String 类型值

package com.wsjzzcbq.java.thread;

import java.time.LocalDateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * Name
 *
 * @author wsjz
 * @date 2023/09/12
 */
public class Name implements Callable {
    @Override
    public String call() throws Exception {
        //为了方便测试线程,让线程睡眠4秒钟
        System.out.println("开始执行:" + LocalDateTime.now());
        TimeUnit.SECONDS.sleep(4);
        return "来是空言去绝踪,月斜楼上五更钟";
    }
}

新建 CallableLearn 类,用于测试

package com.wsjzzcbq.java.thread;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * CallableLearn
 *
 * @author wsjz
 * @date 2023/09/12
 */
public class CallableLearn {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Name name = new Name();
        FutureTask futureTask = new FutureTask<>(name);
        new Thread(futureTask).start();
        //获取返回值
        String returnValue = futureTask.get();
        System.out.println("获取结果:" + LocalDateTime.now());
        System.out.println(returnValue);
    }
}

测试运行

Callable 和 FutureTask 带返回值线程使用和源码分析_第1张图片

可以看到,在线程运行完 Name类中 call方法后,futureTask.get() 获取到线程执行结果

2、源码分析

futureTask.get() 是怎么拿到线程执行的结果的呢?下面分析

首先,大家想一个事情。线程是异步的,彼此之间是没有通信的。即主线程不知道执行call方法的线程什么时候执行完,所以在主线程没有拿到返回值之前它一定是处于等待的状态,而主线程能拿到结果,线程的run方法又是没有返回值的,所以一定是执行call方法的线程执行完,将结果存放起来,然后通知主线程“我”执行完了,然后主线程从“存放的地方”获取结果

下面看源码

先看FutureTask

FutureTask 可以作为Thread 类构造函数的参数,说明它一定实现了 Runnable 接口

看源码知道 实现了 RunnableFuture 接口,而 RunnableFuture 同时实现了 Runnable 接口和Future 接口

Callable 和 FutureTask 带返回值线程使用和源码分析_第2张图片

RunnableFuture

Callable 和 FutureTask 带返回值线程使用和源码分析_第3张图片

下面分析 FutureTask

看下图代码

Callable 和 FutureTask 带返回值线程使用和源码分析_第4张图片

new Thread,创建一个线程,并调用线程的 start 方法,当线程运行起来时,实际是运行 Runnable 中的 run 方法,FutureTask 实现了Runnable 的 run 方法,则会运行 FutureTask中的run 方法,我们直接看 FutureTask 中的 run方法

下面是 FutureTask 中的 run方法

    public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable 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);
        }
    }

run方法中的 state 是从哪来的?我们先看它的构造函数

    /**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Callable}.
     *
     * @param  callable the callable task
     * @throws NullPointerException if the callable is null
     */
    public FutureTask(Callable callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

在构造函数中,传入Callable 接口实现,并将它赋值给变量 callable,然后让state 的值等于 NEW

NEW又是什么呢?看 FutureTask 的成员变量

    /**
     * The run state of this task, initially NEW.  The run state
     * transitions to a terminal state only in methods set,
     * setException, and cancel.  During completion, state may take on
     * transient values of COMPLETING (while outcome is being set) or
     * INTERRUPTING (only while interrupting the runner to satisfy a
     * cancel(true)). Transitions from these intermediate to final
     * states use cheaper ordered/lazy writes because values are unique
     * and cannot be further modified.
     *
     * Possible state transitions:
     * 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;

    /** The underlying callable; nulled out after running */
    private Callable 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;

NEW 的值是0。上面的注释说明了state状态的变化过程,从NEW到 NORMAL,过程结束

下面回到 FutureTask  的 run方法

Callable 和 FutureTask 带返回值线程使用和源码分析_第5张图片

先判断 state 不等于NEW 或者将当前线程赋值给FutureTask 成员变量 runner 失败的话,直接 return

这里因为构造的时候 state已经是NEW了,所以不会进入if 判断,看下面 try 里面的代码,将callable 赋值给 c,判断 c 不等于null 并且 state == NEW,调用c的 call方法,即 Name 类的call方法,call方法运行完成后,将结果赋值给 result 变量,将 ran 变量赋值 true。下面 if(ran) 条件成立,调用set(result)方法

下面看 set(result)方法

    /**
     * Sets the result of this future to the given value unless
     * this future has already been set or has been cancelled.
     *
     * 

This method is invoked internally by the {@link #run} method * upon successful completion of the computation. * * @param v the value */ protected void set(V v) { if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { outcome = v; UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state finishCompletion(); } }

set 方法 UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING) 会以线程安全的方式将 state 修改为 COMPLETING,修改成功则将call 方法返回值赋值给 outcome,然后将state修改为 NORMAL,然后执行 finishCompletion() 方法

    /**
     * Removes and signals all waiting threads, invokes done(), and
     * nulls out callable.
     */
    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
    }

finishCompletion() 方法会先将等待节点 waiters 赋值给 q,然后判断 q 不等于 null,如果 q 不等于空,说明有等待节点,有等待节点的话,UNSAFE.compareAndSwapObject(this, waitersOffset, q, null) 将 waiters 修改为null,然后取出 q 中等待的线程,如果等待的线程不为空的话,使用 LockSupport.unpark(t) 唤醒等待线程

这里读者可能会有疑问,等待节点 waiters 是从哪来的?我们看 FutureTask 的 get 方法

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

这里先判断 state,如果小于等于 COMPLETING 的话,进入 awaitDone(false, 0L),否则直接进入report(s)。什么意思?因为 call 方法是单独的线程运行的,所以当主线程 get 的时候,可能call方法已经运行完了,所以这里判断一下状态,一旦运行完了直接进入 report(s),就不用等待了

我们先看 awaitDone(false, 0L) 方法

    /**
     * Awaits completion or aborts on interrupt or timeout.
     *
     * @param timed true if use timed waits
     * @param nanos time to wait, if timed
     * @return state upon completion
     */
    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);
        }
    }

这里是一个死循环,先判断线程有没有中断;然后判断 state 是不是已经完成 COMPLETING,如果是 COMPLETING ,直接返回;下面判断 q 等于null的话,新建 WaitNode 等于 q,new WaitNode 的时候会把当前线程放进去;之后如果 queued 等于 false 的话,会通过 queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q) 将 q 赋值给 waiters;最后如果其他 if 情况都没进的话,执行 LockSupport.park(this) 让线程阻塞

WaitNode

    /**
     * Simple linked list nodes to record waiting threads in a Treiber
     * stack.  See other classes such as Phaser and SynchronousQueue
     * for more detailed explanation.
     */
    static final class WaitNode {
        volatile Thread thread;
        volatile WaitNode next;
        WaitNode() { thread = Thread.currentThread(); }
    }

这里我们假设 call 方法执行时间很长,当前 get 的时候它还没执行完,初始 WaitNode q = null,所以会进入if分支 q = new WaitNode(),进入下一次循环,如果这时 call 方法还没执行完成,会进入分支 queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q),然后进入下一轮循环,进入最后的 else 分支 LockSupport.park(this) ,让当前 get 的线程等待。然后回顾上面当 call 方法执行完成后,会调用 finishCompletion() 方法唤醒等待的线程,即唤醒调用 get 方法阻塞的线程,调用 get 方法阻塞的线程被唤醒后,会继续开始新一轮循环,此时 state 等于 NORMAL,大于 COMPLETING,直接 return 返回。返回后进入 report(s) 方法

    /**
     * Returns result or throws exception for completed task.
     *
     * @param s completed state value
     */
    @SuppressWarnings("unchecked")
    private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
            return (V)x;
        if (s >= CANCELLED)
            throw new CancellationException();
        throw new ExecutionException((Throwable)x);
    }

state 等于 NORMAL,返回 outcome,即 call 方法的返回值。此时 get 方法拿到 call 方法的返回值

至此完

你可能感兴趣的:(java,源码,面试,java)