程序笔记   发布时间:2022-07-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了FutureTask相关大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
  • 上周因为项目中的线程池参数设置的不合理,引发了一些问题,看了下代码,发现对JUC中的一些概念需要再清晰些。

Runnable

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implemenTing interface <code>Runnable</code> is used
     * to create a thread, starTing the thread causes the object's
     * <code>run</code> method to be called in that separately execuTing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.THREAD#run()
     */
    public abstract void run();
}
  • Runable是一个interface,定义了run()方法,The RunnablE interface should be implemented by any class whose instances arE intended to be executed by a thread。如果想在其他线程中执行你的task,需要实现这个接口。

Callable

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}
  • 有了Runnable,为啥还需要Callable呢,可以看到Runnable和Callable的两个不同,第一,Runnable是没有返回值的,第二,Runnable是不会抛出checked exception的,而有时候我们需要知道任务执行之后的返回,同时也希望利用异常机制完成一些逻辑。所以有了Callable。
  • JUC中的Executors这个Factory类,提供了Runnable转Callable的方法。

Future

  • future 是一个inteface,提供了一系列方法,来帮助我们获取异步执行的task的执行状况和执行结果。

FutureTask

  • FutureTask实现了RunnableFuture接口,即既实现了Runnable接口,又实现了Future接口。所以他有两个功能,第一,作为一个task,提交到别的线程中异步执行,第二,通过future提供的一些接口,获取task的异步执行状态。
/**
     * 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<V> 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;
  • 看下FutureTask的几个属性,首先state表示当前task的执行状态,其中,开始状态位NEW表示task还没开始执行。NORMAL,CANCELLED,INTERRUPTED为终态,COMPLETinG和INTERRUPTinG为临时状态,最终会通过上面的几个状态转移路径,转移到终态。
  • callable,表示具体执行的任务。
  • outcome, task 执行的返回结果
  • runner,执行这个task的线程
  • waiters,通过get方法获取此task执行结果被阻塞的线程。
  • 看下几个核心的方法,我们知道,futuretask提交到别的线程里后,最终会调用task的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方法执行时,首先检查当前的状态是否是NEW,如果不是NEW说明已经被执行过了。开始执行之前,标记执行当前task的线程到runner。
  • 调用callable的run方法,执行。抛异常时,设置setException。正常结束时,set结果。看下这两步里都会调到的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
    }
  • 这里主要是在通知所有阻塞在watch这个task结果的线程,通知他们当前task已经执行结束了。
  • 在执行结束时,看到finally里还有段逻辑
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);
        }

private void handlePossibleCancellationInterrupt(int s) {
        // it is possible for our interrupter to stall before getTing a
        // chance to interrupt us.  Let's spin-wait patiently.
        if (s == INTERRUPTinG)
            while (state == INTERRUPTinG)
                Thread.yield(); // wait out pending interrupt

        // assert state == INTERRUPTED;

        // We want to clear any interrupt we may have received from
        // cancel(true).  However, it is permissible to usE interrupts
        // as an independent mechanism for a task to communicate with
        // its caller, and there is no way to clear only the
        // cancellation interrupt.
        //
        // Thread.interrupted();
    }
  • 这是在干嘛呢,是因为,即使我们在上一步通过set或者setException设置了当前task的状态,但可能有别的线程在通过调用cancel来设置当前task的状态,如果有的话,这里就自旋空转,直到cancel方法执行结束。
  • 那cancel方法是怎么工作的呢
public Boolean cancel(Boolean mayInterruptIfRunning) {
        if (!(state == NEW &&
              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
                  mayInterruptIfRunning ? INTERRUPTinG : CANCELLED)))
            return false;
        try {    // in case call to interrupt throws exception
            if (mayInterruptIfRunning) {
                try {
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // final state
                    UNSAFE.putorderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }
  • cancel方法其实就是通过找到执行当前task的runner,然后调用thread的interrupt方法,这里需要注意的是,thread.interrupt方法仅仅是设置一个标志位,具体线程有没有响应,要看自己的实现。反正这里就是调一把interrupt然后就走了,然后通知所有watch的线程。
  • watch的线程,通过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);
        }
    }
  • 核心逻辑就是,先把自己这个线程放到watch的waitNodes栈中,然后park 等待,直到task的状态>COMPLETinG.

reference

  • https://segmentfault.com/a/1190000016572591
  • https://segmentfault.com/a/1190000016542779

大佬总结

以上是大佬教程为你收集整理的FutureTask相关全部内容,希望文章能够帮你解决FutureTask相关所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。