Java的Future模式

  Java中的Future模式主要是用于等待子线程的返回结果,但是如果一直等待子线程返回值,就会使得主线程阻塞,但其实等待子线程返回值的这段过程中,主线程可以去做其他的事情,不一定要阻塞在原地,Java的Future模式会先返回一个虚拟的结果(假的),主线程可以先去做其他的事情,然后再去获取真实的结果。

  之前Java实现多线程的那篇博客https://www.cnblogs.com/xiaobaituyun/p/10711717.html中有提及,Java可以通过实现Callable接口并重写call函数来实现多线程,然后将实现了callable的对象作为参数来构造FutureTask,FutureTask本身其实是一个runnable,再通过这个futureTask去构造一个Thread,最后通过futureTask的get来获取结果。这就是一个Java的Future模式。

public class MyCallable implements Callable<Integer> {
    @Override
    /**
     * 重写call方法,即为线程的执行体
     */
    public Integer call() throws Exception {
        int i = 0;
        for (; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
        return i;
    }
 
    public static void main(String[] args) {
        //获取实习callable接口的类的实例
        MyCallable callable = new MyCallable();
        //使用FutureTask类来包装Callable对象,
        // 该FutureTask对象封装了该Callable对象的call()方法的返回值。
        FutureTask<Integer> task = new FutureTask<>(callable);
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
            if (i == 20) {
                new Thread(task, "有返回值的线程").start();
                try {
                    System.out.println("子线程的返回值:" + task.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  这里的FutureTask实现了RunnableFuture接口,而这个接口又同时继承了Runnable和Future接口。

public class FutureTask<V> implements RunnableFuture<V> 
public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

  而这里的Future接口主要有以下几个函数:

public interface Future<V> {
  //任务还没执行完成,取消任务,这里的mayInterruptIfRunning代表任务执行过程中能否被中断 boolean cancel(boolean mayInterruptIfRunning);   //任务是否被取消 boolean isCancelled();   //任务是否执行完成 boolean isDone();   //获取任务结果 V get() throws InterruptedException, ExecutionException;   //超时的获取任务结果 V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }

  其中的get函数获取任务结果的,而当任务没有执行完成或者未启动的时候,调用这个方法会导致线程阻塞,当任务已完成后,调用该方法立即返回值或是抛出异常。

  而FutureTask是有任务状态之间的转换的,这里任务的state会在这7种状态中转换。

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;

几种常见的任务状态转换过程:

  1)执行过程顺利完成:NEW -> COMPLETING -> NORMAL

  2)执行过程出现异常:NEW -> COMPLETING -> EXCEPTIONAL

  3)执行过程被取消:NEW -> CANCELLED

  4)执行过程中,线程中断:NEW -> INTERRUPTING -> INTERRUPTED

 

FutureTask的构造函数

  可以从构造函数中看出FutureTask主要有两个参数,一个是callable,另外一个是state,当新建任务的时候,state为NEW,而不论传入的是runnable还是callable,最终都会构造成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
    }

  FutureTask其实也是一个runnable,当调用thread.start()方法时,最终会执行runnable的run()方法。

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

  这里run方法的逻辑主要是将FutureTask执行线程runner进行CAS设置,执行callable,并获取callable的结果,使用set(result)对结果进行保存,当出现异常时,也要对异常进行保存。

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

  进入set方法,设置结果方法开始,状态变为COMPLETING,状态设置成功之后变为NORMAL,最后调用了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函数来获取我们想要的结果,而这里超时和非超时获取结果都是通过awaitDone函数。

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

    public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

  awaitDone函数的逻辑则是如果任务已经执行完成,那么直接返回结果,如果任务还没到set(ressult)那一个阶段,将任务构造成等待任务队列节点放到等待任务队列中,并阻塞当前线程,这就是为啥set函数要进行唤醒,起到了一个等待/通知的作用。

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

  这里的FutureTask.get()其实也是一个阻塞的方法,但是如果说线程已经执行完成,它是直接返回的,如果说线程还在执行,它需要等待线程执行完成,但是在FutureTask.get()之前可以做别的事情(写别的代码逻辑),而不是一直等待线程执行完成。

转载于:https://www.cnblogs.com/xiaobaituyun/p/10820246.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值