Semaphore&阻塞队列
2020-07-14 11:56:17 23 举报
Semaphore&阻塞队列
作者其他创作
大纲/内容
LockSupport.unpark(head.next.thread)
将结点加入到同步队列
setHead(node)
判断线程是否可阻塞(waitStatus ==SIGNAL),不可则更改node结点状态为SIGNAL
next
null
FairSync
队列是否为空
acquire()
int next = current + releases;
notEmpty&¬Full都是条件队列
ArrayBlockingQueue
Thread
CANCELLED:已取消
notFull.signal()
被唤醒
fullyRelease(node)
permits
release()
若加锁之后的剩余次数
获取锁
Node
enqueue(e)
入队
sync.releaseShared(1)
队列中是否有其他线程
CAS恢复可加锁次数
将当前node结点设为头结点
lock.lockInterruptibly()
将first结点转移到同步队列
remaining < 0
prev
将新结点放入队尾
doAcquireSharedInterruptibly(arg)
true
尝试加锁
0:状态为初始值
addWaiter(Node.SHARED)
出队
Semaphore
当前结点是否不在同步队列
tryRelease(arg)
E x = (E) items[takeIndex]items[takeIndex] = null;
结束
CONDITION:条件队列
条件队列
unparkSuccessor(h)
doReleaseShared()
unparkSuccessor(head)
int available = getState()
唤醒同步队列最前的等待唤醒结点
parkAndCheckInterrupt()
take()
tail == null
while (!isOnSyncQueue(node))
notEmpty.signal()
release(savedState)
firstWaiter
doSignal(first)
int savedState = getState()
compareAndSetHead(new Node())
r>=0
items[putIndex] = x
tryAcquireShared(acquires)
解锁,这里会唤醒同步队列中的结点
hasQueuedPredecessors()
解锁
Node p = node.predecessor()
lock.unlock()
当前剩余加锁次数+解锁次数
获取加锁次数
将first结点指向下一个结点
将notEmpty中的结点转移到同步队列
notFull.await()
重新加锁
notEmpty.await()
NonfairSync
tryReleaseShared(arg)
尝试加锁失败,将当前线程入队等待
int current = getState();
transferForSignal(first)
enq(node);
将notFull队列中的结点转移至同步队列
Tail
释放锁
将当前线程封装成node放入队尾
if (++putIndex == items.length) putIndex = 0;
Head
唤醒其他等待线程
Node node = addConditionWaiter()
int r = tryAcquireShared(arg);
while (count == items.length)
同步队列
释放所有锁次数
count--;
SIGNAL:等待被唤醒
put(E e)
唤醒排在队列最前面的SIGNAL结点
LockSupport.park(this)
int remaining = available - acquires;
enq(node)
dequeue()
while (count == 0)
p == head
队列是否已满
false
count++
firstWaiter = first.nextWaiter
将结点加入条件队列
sync.acquireSharedInterruptibly(1)
if (++takeIndex == items.length) takeIndex = 0;
0 条评论
下一页