FutureTask

1. 作用

  • 异步操作
  • 获取执行结果
  • 取消任务执行,判断是否取消执行
  • 判断任务执行是否完毕

2. demo


    public static void main(String[] args) throws Exception {
        Callable callable= () -> search();

        FutureTask futureTask=new FutureTask<>(callable);
        futureTask.run();

        // 持续阻塞
        String s = futureTask.get();

        System.out.println(s);
        System.out.println("主线程收集了1颗龙珠");
    }

    /**
     * 收集龙珠
     */
    public static String search() {

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "找到了1颗龙珠";
    }

3. 原理

3.1 类关系图

FutureTask_第1张图片

3.2 主要流程

FutureTask_第2张图片

3.3 方法

3.3.1 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)

                    // 将结果赋值给outcome
                    set(result);
            }
        } finally {
     
            runner = null;
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }


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

3.3.2 futureTask.get()

    public V get() throws InterruptedException, ExecutionException {
        // 当前状态未完成时,进入自旋等待
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);

        // 返回子进程的执行结果
        return report(s);
    }



    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;
                }
                
                // 多次等待后park一会(自己会醒)
                LockSupport.parkNanos(this, nanos);
            }
            else
                // 多次等待后park一会(自己不会醒)
                LockSupport.park(this);
        }
    }

    // 获取结果
    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);
    }

你可能感兴趣的:(并发编程,java)