当前位置: 移动技术网 > IT编程>开发语言>Java > 了解JAVA并发工具常用设计套路

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

前言

在学习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并发编程中的套路,抓住这个思路,想必能在学习中有所帮助。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网