这篇文章主要介绍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并发工具常用设计的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。