Java并发编程之FutureTask源码解析

上次总结一下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为什么能有返回值以及基本运行机制应该有个初步的了解,可以自行的去多看几遍。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/537169.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java 删除二维数组中的null_避免在Java中检查Null语句

1.概述通常&#xff0c;在Java代码中处理null变量、引用和集合很棘手。它们不仅难以识别&#xff0c;而且处理起来也很复杂。事实上&#xff0c;在编译时无法识别处理null的任何错误&#xff0c;会导致运行时NullPointerException。在本教程中&#xff0c;我们将了解在Java中检…

Java并发编程之并发容器ConcurrentHashMap(JDK1.7)解析

最近看了一下ConcurrentHashMap的相关代码&#xff0c;感觉JDK1.7和JDK1.8差别挺大的&#xff0c;这次先看下JDK1.7是怎么实现的吧 哈希&#xff08;hash&#xff09; 先了解一下啥是哈希&#xff08;网上有很多介绍&#xff09;&#xff0c;是一种散列函数&#xff0c;简单来…

带控制端的逻辑运算电路_分别完成正整数的平方、立方和阶乘的运算verilog语言...

练习&#xff1a;设计一个带控制端的逻辑运算电路&#xff0c;分别完成正整数的平方、立方和阶乘的运算。 //--------------myfunction---------- modulemyfunction(clk,n,result,reset,sl); output[6:0]result; input[2:0] n; input reset,clk; input [1:0] sl; reg[6:0]resul…

Java并发编程之并发容器ConcurrentHashMap(JDK1.8)解析

这个版本ConcurrentHashMap难度提升了很多&#xff0c;就简单的谈一下常用的方法就好了&#xff0c;可能有些讲的不太清楚&#xff0c;麻烦发现的大佬指正一下 主要数据结构 1.8将Segment取消了&#xff0c;保留了table数组的形式&#xff0c;但是不在以HashEntry纯链表的形式…

simulink显示多个数据_如何在 Simulink 中使用 PID Tuner 进行 PID 调参?

作者 | 安布奇责编 | 胡雪蕊出品 | CSDN(ID: CSDNnews)本文为一篇技术干货&#xff0c;主要讲述在Simulink如何使用PID Tuner进行PID调参。PID调参器( PIDTuner)概述1.1 简介使用PID Tuner可以对Simulink模型中的PID控制器&#xff0c;离散PID控制器&#xff0c;两自由度PID控制…

Java并发编程之堵塞队列介绍以及SkipList(跳表)

堵塞队列 先了解一下生产者消费者模式&#xff1a; 生产者就是生产数据的一方&#xff0c;消费者就是消费数据的另一方。在多线程开发中&#xff0c;如果生产者处理速度很快&#xff0c;而消费者处理速度很慢&#xff0c;那么生产者就必须等待消费者处理完&#xff0c;才能继…

python生成list的时候 可以用lamda也可以不用_python 可迭代对象,迭代器和生成器,lambda表达式...

分页查找#5.随意写一个20行以上的文件(divmod)# 运行程序&#xff0c;先将内容读到内存中&#xff0c;用列表存储。# l []# 提示&#xff1a;一共有多少页# 接收用户输入页码&#xff0c;每页5条&#xff0c;仅输出当页的内容def read_page(bk_list,n,endlineNone):startline …

数据挖掘技术简介[转]

关键词&#xff1a; 关键词&#xff1a;数据挖掘 数据集合 1. 引言  数据挖掘(Data Mining)是从大量的、不完全的、有噪声的、模糊的、随机的数据中提取隐含在其中的、人们事先不知道的、但又是潜在有用的信息和知识的过程。随…

树莓派安装smbus_树莓派使用smbus不兼容问题(no module named 'smbus')

树莓派使用smbus不兼容问题(no module named ‘smbus’)python3.5–3.6可以使用smbus2代替smbus1. 先参考以下方法&#xff1a;github讨论树莓派社区2.Pypi上可以下载smbus2smbus2PyPi介绍&#xff1a;当前支持的功能有&#xff1a;获取i2c功能(I2C_FUNCS)read_bytewrite_byter…

Java并发编程之线程池ThreadPoolExecutor解析

线程池存在的意义 平常使用线程即new Thread()然后调用start()方法去启动这个线程&#xff0c;但是在频繁的业务情况下如果在生产环境大量的创建Thread对象是则会浪费资源&#xff0c;不仅增加GC回收压力&#xff0c;并且还浪费了时间&#xff0c;创建线程是需要花时间的&…

面向过程的门面模式

{*******************************************************}{ }{ 业务逻辑一 }{ }{ 版权所有 (C) 2008 陈…

Java并发编程之线程定时器ScheduledThreadPoolExecutor解析

定时器 就是需要周期性的执行任务&#xff0c;也叫调度任务&#xff0c;在JDK中有个类Timer是支持周期性执行&#xff0c;但是这个类不建议使用了。 ScheduledThreadPoolExecutor 继承自ThreadPoolExecutor线程池&#xff0c;在Executors默认创建了两种&#xff1a; newSin…

python xml转换键值对_Python 提取dict转换为xml/json/table并输出

#!/usr/bin/python#-*- coding:gbk -*-#设置源文件输出格式import sysimport getoptimport jsonimport createDictimport myConToXMLimport myConToTabledef getRsDataToDict():#获取控制台中输入的参数&#xff0c;并根据参数找到源文件获取源数据csDict{}try:#通过getopt获取…

应用开发框架之——根据数据表中的存储的方法名称来调用方法

功用一&#xff1a;在框架里面根据存储在数据表中的方法名来动态调用执行方法。 unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 class(TForm) Button1: TButton; procedu…

Spring IOC容器组件注入的几种方式

整理一下之前Spring的学习笔记&#xff0c;大致有一下几种Spring注入到容器中的方法: 1&#xff09;、配置在xml的方式。 2&#xff09;、开启包扫描ComponentScan使用Component&#xff0c;Service&#xff0c;Controller&#xff0c;Repository&#xff08;其实后三个都继承…

我们是如何拿下Google和Facebook Offer的?

http://posts.careerengine.us/p/57c3a1c1a09633ee7e57803c 大家好&#xff0c;我是小高&#xff0c;CMU CS Master&#xff0c;来Offer第一期学员&#xff0c;2014年初在孙老师的带领下我在几个月的时间内进入了Yahoo&#xff0c;并工作了近2年。2016年初&#xff0c;Yahoo工作…

Spring中BeanFactory和FactoryBean的区别

先介绍一下Spring的IOC容器到底是个什么东西&#xff0c;都说是一个控制反转的容器&#xff0c;将对象的控制权交给IOC容器&#xff0c;其实在看了源代码之后&#xff0c;就会发现IOC容器只是一个存储单例的一个ConcurrentHashMap<String, BeanDefinition> BeanDefiniti…

python中数字和字符串可以直接相加_用c语言或者python将文件中特定字符串后面的数字相加...

匿名用户1级2014-08-31 回答代码应该不难吧。既然用爬虫爬下来了&#xff0c;为什么爬取数据的时候没做处理呢。之前用过Scrapy爬虫框架&#xff0c;挺好用的&#xff0c;你可研究下。代码&#xff1a;#!codingutf-8import osimport reimport random# 获取当前目录文件列表def …

Spring中Aware的用法以及实现

Aware 在Spring当中有一些内置的对象是未开放给我们使用的&#xff0c;例如Spring的上下文ApplicationContext、环境属性Environment&#xff0c;BeanFactory等等其他的一些内置对象&#xff0c;而在我们可以通过实现对应的Aware接口去拿到我们想要的一些属性&#xff0c;一般…