上次总结一下AQS的一些相关知识,这次总结了一下FutureTask的东西,相对于AQS来说简单好多呀

之前提到过一个LockSupport的工具类,也了解一下这个工具类的用法,这里也巩固一下吧

    /*** Makes available the permit for the given thread, if it* was not already available.  If the thread was blocked on* {@code park} then it will unblock.  Otherwise, its next call* to {@code park} is guaranteed not to block. This operation* is not guaranteed to have any effect at all if the given* thread has not been started.** @param thread the thread to unpark, or {@code null}, in which case*        this operation has no effect*///将指定线程唤醒,继续执行指定线程public static void unpark(Thread thread) {if (thread != null)UNSAFE.unpark(thread);}    /*** Disables the current thread for thread scheduling purposes unless the* permit is available.** <p>If the permit is available then it is consumed and the call* returns immediately; otherwise the current thread becomes disabled* for thread scheduling purposes and lies dormant until one of three* things happens:** <ul>** <li>Some other thread invokes {@link #unpark unpark} with the* current thread as the target; or** <li>Some other thread {@linkplain Thread#interrupt interrupts}* the current thread; or** <li>The call spuriously (that is, for no reason) returns.* </ul>** <p>This method does <em>not</em> report which of these caused the* method to return. Callers should re-check the conditions which caused* the thread to park in the first place. Callers may also determine,* for example, the interrupt status of the thread upon return.*///阻塞当前线程,等待调用unpark()唤醒当前线程public static void park() {UNSAFE.park(false, 0L);}// Hotspot implementation via intrinsics APIprivate static final sun.misc.Unsafe UNSAFE;

就是阻塞线程以及唤醒指定线程,在FutureTask的源码中能用到

RunnableFuture<V>

FutureTask继承自这个接口,这个接口有继承了Runnable以及Future接口,所以FutureTask对象可以用new Thread().start()去启动,所以之前提到了创建线程的三种方式,采用Callable+FutureTask的形式创建,依旧还是依赖于Runnable创建线程

/*** A {@link Future} that is {@link Runnable}. Successful execution of* the {@code run} method causes completion of the {@code Future}* and allows access to its results.* @see FutureTask* @see Executor* @since 1.6* @author Doug Lea* @param <V> The result type returned by this Future's {@code get} method*/
public interface RunnableFuture<V> extends Runnable, Future<V> {/*** Sets this Future to the result of its computation* unless it has been cancelled.*/void run();
}

源码解析

既然继承了Runnable接口就必然执行run()方法,我们先看下主要成员变量

    /*** 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 *///Callable对象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;//单向链表static final class WaitNode {volatile Thread thread;//记录当前线程volatile WaitNode next;//下一个节点WaitNode() { thread = Thread.currentThread(); }}

看一下执行主体,这个方法主要是将Callable对象的那个业务逻辑执行完毕,只有执行完成之后采用将值返回,并且将当前线程通过LockSupport.unpark()进行唤醒。

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();//调用Callable对象并执行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);}}/*** 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 gcq = next;}break;}}done();callable = null;        // to reduce footprint}

看一下Future的结果值的方法,每步方法在代码中都有讲解

    /*** @throws CancellationException {@inheritDoc}*/public V get() throws InterruptedException, ExecutionException {int s = state;//先判断当前线程的执行状态是否执行完毕,未执行完的则调用等待方法if (s <= COMPLETING)s = awaitDone(false, 0L);return report(s);}/*** Awaits completion or aborts on interrupt or timeout.** @param timed true if use timed waits* @param nanos time to wait, if timed* @return state upon completion*///方法就是用过LockSupport.park()进入线程等待方法,等待调用unpark然后在次判断是否执行完,执行完后将改方法结束,进入下一阶段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 yetThread.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);}elseLockSupport.park(this);}}/*** Returns result or throws exception for completed task.** @param s completed state value*/@SuppressWarnings("unchecked")//在等待完之后,再次判断是否正常完成执行,正常的话将值返回,否则抛出异常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);}

通过上面的讲解,应该对FutureTask为什么能有返回值以及基本运行机制应该有个初步的了解,可以自行的去多看几遍。

Java并发编程之FutureTask源码解析相关推荐

  1. Java并发编程之CountDownLatch源码解析

    一.导语 最近在学习并发编程原理,所以准备整理一下自己学到的知识,先写一篇CountDownLatch的源码分析,之后希望可以慢慢写完整个并发编程. 二.什么是CountDownLatch Count ...

  2. Java并发编程之ThreadLocal源码分析

    1 一句话概括ThreadLocal   什么是ThreadLocal?顾名思义:线程本地变量,它为每个使用该对象的线程创建了一个独立的变量副本. 2 ThreadLocal使用场景   用一句话总结 ...

  3. Android 网络编程之OkHttp源码解析

    前言:OkHttp框架是Android的网络请求框架,无数的项目都在使用着这个框架,重要性不言而喻; 本文会将OKHTTP的源码进行拆解,每个部分来单独学习,由简入深,循序渐进,篇幅较长,建议收藏,慢 ...

  4. Java并发修改异常的源码解析

    1. 什么时候会产生并发修改异常 并发的意思是同时发生,那么其实并发修改的字面意思就是同时修改,通过查看JDK的API我们可以得知,并发修改异常的出现的原因是:当方法检测到对象的并发修改,但不允许这种 ...

  5. 并发编程之 Semaphore 源码分析

    前言 并发 JUC 包提供了很多工具类,比如之前说的 CountDownLatch,CyclicBarrier ,今天说说这个 Semaphore--信号量,关于他的使用请查看往期文章并发编程之 线程 ...

  6. 并发编程之 ThreadLocal 源码剖析

    前言 首先看看 JDK 文档的描述: 该类提供了线程局部 (thread-local) 变量.这些变量不同于它们的普通对应物,因为访问某个变量(通过其 get 或 set 方法)的每个线程都有自己的局 ...

  7. Java 并发编程之 FutureTask

    FutureTask 类构造函数参数为 Callable 接口,实现 RunnableFuture 接口,而 RunnableFuture 接口继承了 Future 和 Runnable 接口, 所以 ...

  8. Java并发编程之CyclicBarrier详解

    简介 栅栏类似于闭锁,它能阻塞一组线程直到某个事件的发生.栅栏与闭锁的关键区别在于,所有的线程必须同时到达栅栏位置,才能继续执行.闭锁用于等待事件,而栅栏用于等待其他线程. CyclicBarrier ...

  9. Java并发编程之CAS第三篇-CAS的缺点

    Java并发编程之CAS第三篇-CAS的缺点 通过前两篇的文章介绍,我们知道了CAS是什么以及查看源码了解CAS原理.那么在多线程并发环境中,的缺点是什么呢?这篇文章我们就来讨论讨论 本篇是<凯 ...

最新文章

  1. php 二维数组排序,多维数组排序
  2. d3.js 旋转图形_【IOS游戏推荐】百万畅销游戏刚从STEAM移植至IOS平台,在极端地形中冒险前进!——旋转轮胎:泥泞奔驰...
  3. Java中isAssignableFrom的用法
  4. saiku 3.8 二次开发代码整理步骤(20160727更新)
  5. free是自由,不是免费,从王开源说起
  6. 谈谈招聘时我喜欢见到的特质
  7. A02_Python(基本数据类型,容器,函数,类),Numpy(数组array,数组索引,数据类型,数组中的数学,广播)
  8. Java中的HashMap和HashTable到底哪不同?(原文参考来自码农网)
  9. 智能合约开发solidity编程语言实例
  10. RapidMiner数据挖掘入门
  11. 小米更新显示非官方rom_MIUI官改篇对比分析-极光ROM-台湾W大-星空未来-其他官改官网...
  12. Windows7 问题集 - McAfee、迷你迅雷、Dropbox
  13. Java基础Day05
  14. 适合运动健身的蓝牙耳机推荐,六款适合运动健身的蓝牙耳机
  15. Web前端 vs Web后端 区别是什么
  16. 位图字体生成工具 BMFont汉化版
  17. 浮点数与十六进制互相转换
  18. 微信支付接口调用之二维码失效时间的设置
  19. 总结整理时下流行的浏览器User-Agent大全
  20. Samplitude pro x4完美汉化破解版|Samplitude pro x4 64位完美汉化破解版(附汉化包)下载 v15.0.1.139

热门文章

  1. android开机自动开启zram,低内存配置  |  Android 开源项目  |  Android Open Source Project...
  2. 计算机专业人毕业设计外文翻译,计算机专业毕业设计外文翻译.doc
  3. 用友邮件撤回怎么操作_用户体验原则——“操作可控”
  4. 通过微型计算机的电流,单板微型计算机控制的电流型变频调速系统
  5. lintcode 落单的数(位操作)
  6. 大学计算机基础总结,大学计算机基础第二章总结
  7. git安装后找不见版本_结果发现git版本为1.7.4,(git --version)而官方提示必须是1.7.10及以后版本...
  8. 攻防世界web2(逆向加密算法)
  9. 扫掠两条引导线_《神都夜行录》周年庆点燃线上线下,解读国风二次元IP的成长之路...
  10. linux流式访问日志,流式实时日志分析系统的实现原理