JAVA并发工具常用设计的示例分析
这篇文章主要介绍JAVA并发工具常用设计的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
创新互联长期为近千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为鄂托克前企业提供专业的成都做网站、网站制作,鄂托克前网站改版等技术服务。拥有10余年丰富建站经验和众多成功案例,为您定制开发。
前言
在学习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并发工具常用设计的示例分析
标题来源:http://myzitong.com/article/gjjioj.html