使用多线程的方式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("主线程执行完毕");

    }
}

运行测试(无返回值)

实现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("主线程执行完毕");
    }
}

运行测试(有返回值)

探究一下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了?于是我们就拿到了返回值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值