天天看点

使用多线程的方式3---callable(带返回值)及FutureTask原理

目录

实现callable接口(无返回值)

创建FutureTask实例(无返回值)

运行测试(无返回值)

实现callable接口(有返回值)

创建FutureTask实例(有返回值)

运行测试(有返回值)

探究一下futureTask

多线程使用方式---实现callable接口

实现callable接口(无返回值)

package my.notes;

import java.util.concurrent.Callable;

public class MyCallable implements Callable {
    @Override
    public Object call() throws Exception {
        System.out.println("实现callable");
        return null;
    }
}
           

创建FutureTask实例(无返回值)

package my.notes;

import java.util.concurrent.FutureTask;

public class MyTest {
    public static void main(String[] args) {

        System.out.println("主线程开始执行");
        MyCallable myCallable = new MyCallable();
        FutureTask futureTask = new FutureTask(myCallable);
        futureTask.run();
        System.out.println("主线程执行完毕");

    }
}
           

运行测试(无返回值)

使用多线程的方式3---callable(带返回值)及FutureTask原理

实现callable接口(有返回值)

package my.notes;

import java.util.concurrent.Callable;

public class MyCallable implements Callable {
    @Override
    public Object call() throws Exception {
        System.out.println("实现callable");
        return "这是一个返回值晓得吧?";
    }
}
           

创建FutureTask实例(有返回值)

package my.notes;

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

public class MyTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        System.out.println("主线程开始执行");
        MyCallable myCallable = new MyCallable();
        FutureTask futureTask = new FutureTask(myCallable);
        futureTask.run();
        System.out.println("callable返回值:" + futureTask.get());
        System.out.println("主线程执行完毕");
    }
}
           

运行测试(有返回值)

使用多线程的方式3---callable(带返回值)及FutureTask原理

探究一下futureTask

public class FutureTask<V> implements RunnableFuture<V> 
           

构造方法:

public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }
           

来看一眼我们用到的.get方法,毕竟有一个猜测,如果那边线程没执行完,我们去get,会怎么办

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

嗯哼?发现了一个什么,等待,哦~ get不到它会等待,阻塞嘛这不是

都到这儿了,我们继续往下看这个等待是干嘛的

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);
        }
    }
           

Lock,这下就明白了

但是也不態光一直等待啊,有等待肯定就必须有唤醒,继续往下

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);
        }
    }
           

可以看到有一个boolean ran,是一个状态,当我们的callable执行完返回结果,会执行一个set,还把返回值传过去了,我们看看这个set

protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            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
    }
           

注意到了没,释放了线程,还记得我们从哪儿开始看的吗?从get方法开始看的,那我们再回去

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

这个时候是不是注意到了最后一个return了?于是我们就拿到了返回值