FutureTask result的获取

来源:互联网 发布:中国大数据信息 编辑:程序博客网 时间:2024/05/18 08:27

在http://www.blogjava.net/xylz/archive/2011/02/13/344207.html学习了并发中的线程池,作者为了加快速度或者限于篇幅,只介绍了result获取的核心关键,在此补上”源代码里获取result的一个流程”.

jdk版本是1.6.0_43.

public void execute(Runnable command) {        if (command == null)            throw new NullPointerException();        if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {            if (runState == RUNNING && workQueue.offer(command)) {                if (runState != RUNNING || poolSize == 0)                    ensureQueuedTaskHandled(command);            }            else if (!addIfUnderMaximumPoolSize(command))                reject(command); // is shutdown or saturated        }    }/**     * Creates and starts a new thread running firstTask as its first     * task, only if fewer than corePoolSize threads are running     * and the pool is not shut down.     * @param firstTask the task the new thread should run first (or     * null if none)     * @return true if successful     */    private boolean addIfUnderCorePoolSize(Runnable firstTask) {        Thread t = null;        final ReentrantLock mainLock = this.mainLock;        mainLock.lock();        try {            if (poolSize < corePoolSize && runState == RUNNING)                t = addThread(firstTask);        } finally {            mainLock.unlock();        }        return t != null;    }/**     * Creates and returns a new thread running firstTask as its first     * task. Call only while holding mainLock.     *     * @param firstTask the task the new thread should run first (or     * null if none)     * @return the new thread, or null if threadFactory fails to create thread     */    private Thread addThread(Runnable firstTask) {        Worker w = new Worker(firstTask);//Worker也是一个Runnable实现类        Thread t = threadFactory.newThread(w);        boolean workerStarted = false;        if (t != null) {            if (t.isAlive()) // precheck that t is startable                throw new IllegalThreadStateException();            w.thread = t;            workers.add(w);            int nt = ++poolSize;            if (nt > largestPoolSize)                largestPoolSize = nt;            try {                t.start();                workerStarted = true;            }            finally {                if (!workerStarted)                    workers.remove(w);            }        }        return t;    }/**  这个是work中的run方法         * Main run loop         */        public void run() {            try {                hasRun = true;                Runnable task = firstTask;                firstTask = null;                while (task != null || (task = getTask()) != null) {                    runTask(task);                    task = null;                }            } finally {                workerDone(this);            }        }/**         * Runs a single task between before/after methods.         */        private void runTask(Runnable task) {            final ReentrantLock runLock = this.runLock;            runLock.lock();            try {                /*                 * If pool is stopping ensure thread is interrupted;                 * if not, ensure thread is not interrupted. This requires                 * a double-check of state in case the interrupt was                 * cleared concurrently with a shutdownNow -- if so,                 * the interrupt is re-enabled.                 */                if ((runState >= STOP ||                    (Thread.interrupted() && runState >= STOP)) &&                    hasRun)                    thread.interrupt();                /*                 * Track execution state to ensure that afterExecute                 * is called only if task completed or threw                 * exception. Otherwise, the caught runtime exception                 * will have been thrown by afterExecute itself, in                 * which case we don't want to call it again.                 */                boolean ran = false;                beforeExecute(thread, task);                try {/**这个task可以是 FutureTask,public class FutureTask<V> implements RunnableFuture<V>public interface RunnableFuture<V> extends Runnable, Future<V>*/                    task.run();                    ran = true;                    afterExecute(task, null);                    ++completedTasks;                } catch (RuntimeException ex) {                    if (!ran)                        afterExecute(task, ex);                    throw ex;                }            } finally {                runLock.unlock();            }        }//这个是FutureTask类中run方法public void run() {        sync.**innerRun**();    }//sync是FutureTask的内部类//private final class Sync extends AbstractQueuedSynchronizervoid innerRun() {            if (!compareAndSetState(0, RUNNING))                return;            try {                runner = Thread.currentThread();                if (getState() == RUNNING) // recheck after setting thread                    innerSet(callable.call());//这个是callable回调方法                else                    releaseShared(0); // cancel            } catch (Throwable ex) {                innerSetException(ex);            }        } void innerSet(V v) {        for (;;) {        int s = getState();        if (s == RAN)            return;                if (s == CANCELLED) {            // aggressively release to set runner to null,            // in case we are racing with a cancel request            // that will try to interrupt runner                    releaseShared(0);                    return;                }        if (compareAndSetState(s, RAN)) {                    result = v;//result就是运行结果,是sync的一个属性                    releaseShared(0);                    done();            return;                }            }        }//在FutureTask中, public V get() throws InterruptedException, ExecutionException {        return sync.innerGet();    }V innerGet() throws InterruptedException, ExecutionException {            acquireSharedInterruptibly(0);            if (getState() == CANCELLED)                throw new CancellationException();            if (exception != null)                throw new ExecutionException(exception);            return result;//这个result就是运行结果        }

FutureTask不仅是实现了Runnable, 而且还实现了Future,包含了成员属性result。
Run()执行完之后就把结果放到了result,然后通过FutureTask获取result.
具体看代码片段。

原创粉丝点击