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