欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

了解JAVA并发工具常用设计套路

时间:2020-10-29 14:29:20|栏目:JAVA代码|点击:

前言

在学习JAVA并发工具时,分析JUC下的源码,发现有三个利器:状态、队列、CAS。

状态

一般是state属性,如AQS源码中的状态,是整个工具的核心,一般操作的执行都要看当前状态是什么,
由于状态是多线程共享的,所以都是volatile修饰,保证线程直接内存可见。

/**
* AbstractQueuedSynchronizer中的状态
*/
private volatile int state;

/**
* Status field, taking on only the values:
* SIGNAL: The successor of this node is (or will soon be)
* blocked (via park), so the current node must
* unpark its successor when it releases or
* cancels. To avoid races, acquire methods must
* first indicate they need a signal,
* then retry the atomic acquire, and then,
* on failure, block.
* CANCELLED: This node is cancelled due to timeout or interrupt.
* Nodes never leave this state. In particular,
* a thread with cancelled node never again blocks.
* CONDITION: This node is currently on a condition queue.
* It will not be used as a sync queue node
* until transferred, at which time the status
* will be set to 0. (Use of this value here has
* nothing to do with the other uses of the
* field, but simplifies mechanics.)
* PROPAGATE: A releaseShared should be propagated to other
* nodes. This is set (for head node only) in
* doReleaseShared to ensure propagation
* continues, even if other operations have
* since intervened.
* 0: None of the above
*
* The values are arranged numerically to simplify use.
* Non-negative values mean that a node doesn't need to
* signal. So, most code doesn't need to check for particular
* values, just for sign.
*
* The field is initialized to 0 for normal sync nodes, and
* CONDITION for condition nodes. It is modified using CAS
* (or when possible, unconditional volatile writes).
*/
volatile int waitStatus;

队列

队列一般由链表实现(单向链表,双向链表),在线程获取不到想要的资源或者状态时,将线程封装成特定节点,扔到等待队列中,等待时机成熟,再从队列中取出,是悲观锁思想。
如AQS中的Node节点,代码太长就不贴了。

CAS

CAS操作是乐观锁思想,是轻量级的并发处理。一般用于对上述状态的修改,而且能保证有且只有一个线程能修改这个状态。
一般由Unsafe类中的compareAndSwap之类的方法实现。使用CAS,往往伴随自旋,如果修改状态失败,则不断地重试,直到修改状态成功。

以上就是java并发编程中的套路,抓住这个思路,想必能在学习中有所帮助。

上一篇:java读取文件字符集示例方法

栏    目:JAVA代码

下一篇:springboot数据库操作图文教程

本文标题:了解JAVA并发工具常用设计套路

本文地址:http://www.codeinn.net/misctech/17137.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有