final Thread current = Thread.currentThread(); //ASQ中方法,获取当前同步状态,这里的c表示锁重入的数量 int c = getState(); //没有线程持有锁 if (c == 0) { //如果设置成功 if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } //当前线程持有锁 else ...
45 protected final boolean isHeldExclusively() { 46 // While we must in general read state before owner, 47 // we don't need to do so to check if current thread is owner 48 return getExclusiveOwnerThread() == Thread.currentThread(); 49 } 50 //在AQS中的创建ConditionObject对象,保存等待...
Returns the thread that currently owns this lock, or null if not owned. When this method is called by a thread that is not the owner, the return value reflects a best-effort approximation of current lock status. For example, the owner may be momentarily null even if there are threads try...
setExclusiveOwnerThread(current); 设置线程拥有者,setExclusiveOwnerThread是AQS的父类AbstractOwnableSynchronizer接口定义的方法, return true; 成功返回 } } else if (current == getExclusiveOwnerThread()) { 如果目前正在占用同步器, int nextc = c + acquires; 那么直接重入, if (nextc < 0) // overflo...
//设置当前线程为锁的拥有者setExclusiveOwnerThread(current);returntrue; } } //如果锁的持有者已经是当期线程,更新锁的状态,这个地方就是为什么可重入的原因,如果获取锁的线程再次请求,则将同步状态的值增加,并返回true //表明获取同步状态值成功elseif(current ==getExclusiveOwnerThread()) {intnextc = c ...
ReentrantLock 底层加锁是通过 CAS 来更新 AQS 队列中的 state 状态,并且 ReentrantLock 的可重入锁也是...
Otherwise, this thread is eligible for lock if * it is either a reentrant acquire or * queue policy allows it. If so, update state * and set owner. */ Thread current = Thread.currentThread(); int c = getState(); int w = exclusiveCount(c); // 存在读锁或写锁 if (c != 0) ...
{//具体实现原理接下来再讲,意思是设置当前持有锁的对象为此线程setExclusiveOwnerThread(current);return true;}}//如果当前线程已获得锁,则进行重入else if (current == getExclusiveOwnerThread()) {int nextc = c + acquires;if (nextc < 0) // overflowthrow new Error("Maximum lock count exceeded")...
{setExclusiveOwnerThread(current);returntrue;}}// 看看当前的线程是不是锁的持有者elseif(current==getExclusiveOwnerThread()){// 如果是的话 将状态设置为 c + acquiresint nextc=c+acquires;if(nextc<0)// overflowthrownewError("Maximum lock count exceeded");setState(nextc);returntrue;}return...
Queries the number of holds on this lock by the current thread. protectedThreadgetOwner() Returns the thread that currently owns this lock, ornullif not owned. protectedCollection<Thread>getQueuedThreads() Returns a collection containing threads that may be waiting to acquire this lock. ...