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.
具体看代码片段。
阅读全文
0 0
- FutureTask result的获取
- FutureTask(Runnable runnable, V result) 中的result
- FutureTask获取线程返回值
- FutureTask获取线程返回值, 用来获取耗时较长的计算结果
- FutureTask、ExecutorService的使用
- FutureTask的优点
- FutureTask的使用
- FutureTask的使用示例
- FutureTask的用法
- FutureTask的使用
- FutureTask的使用方法
- StartActivityForResult() 和setResult() 方法获取不到result 的BUG
- FutureTask
- FutureTask
- FutureTask
- FutureTask
- FutureTask
- FutureTask
- 圆啊圆
- 1133: 班级人数
- hbase-架构
- [leetcode]152. Maximum Product Subarray
- C# 更改系统时间
- FutureTask result的获取
- 常用无线局域网标准
- Node.js基本模块学习(二)
- 怎样实现同一个账户同一时间只能在一个终端登录
- 点击按钮 “加载更多”效果
- There's no Qt version assigned to this project for platform x64
- Xutils简单介绍
- 网络基础之协议-1
- java设计模式——迭代器模式