å‰é¢ä¸€èŠ?/a>ä¸ï¼Œæˆ‘们分æžäº†ReentrantLock.lock()æ–ÒŽ³•åQŒæŽ¥ä¸‹æ¥æˆ‘们接ç€åˆ†æžReentrantLock.unlock()æ–ÒŽ³•ã€?br />
1.ReentrantLock.unlock()分æž
(1)首先ž®è¯•释放é”ï¼Œå¦‚æžœè¦æ±‚释放数ç‰äºŽé”çŠ¶æ€æ•°åQŒé‚£ä¹ˆå°†é”状æ€ä½æ¸?åQŒæ¸…除锿‰€æœ‰è€…,˜q”回trueåQ›å¦åˆ™è¿”回false;
(2)如果(1)˜q”回的是trueåQŒè¯´æ˜Žé”完全释放。接下楞®†æ£€æŸ¥ç‰å¾…队列,òq‰™€‰æ‹©ä¸€ä¸ªwaitStatus处于½{‰å¾…状æ€çš„节点下的¾U¿ç¨‹unpark(æ¢å¤)åQŒé€‰æ‹©çš„便®æ˜¯ä»Žå°¾èŠ‚ç‚¹å¼€å§‹ï¼Œé€‰å–æœ€é 近头节点的½{‰å¾…节点,åŒæ—¶æ¸…ç†é˜Ÿåˆ—ä¸çº¿½E‹è¢«å–消的节点;
(3)如果(1)˜q”回falseåQŒè¯´æ˜Žé”åªæ˜¯éƒ¨åˆ†é‡Šæ”¾åQŒå½“å‰çº¿½E‹ä»æ—§æŒæœ‰è¯¥é”ï¼›
1
java.util.concurrent.locks.ReentrantLock
2
public void unlock()
{
3
sync.release(1);
4
}
5
6
java.util.concurrent.locks.AbstractQueuedSynchronizer
7
public final boolean release(int arg)
{
8
if (tryRelease(arg))
{
9
Node h = head;
10
if (h != null && h.waitStatus != 0)
11
unparkSuccessor(h);
12
return true;
13
}
14
return false;
15
}
16
17
18
protected final boolean tryRelease(int releases)
{
19
int c = getState() - releases; //é‡å…¥é”åŠ é”çš„‹Æ¡æ•°-释放数é‡
20
if (Thread.currentThread() != getExclusiveOwnerThread()) //判æ–独å 锿˜¯å¦äؓ当剾U¿ç¨‹æ‰€æœ?/span>
21
throw new IllegalMonitorStateException();
22
boolean free = false;
23
if (c == 0)
{ //åŠ é”‹Æ¡æ•°=释放数é‡
24
free = true;
25
setExclusiveOwnerThread(null); //æ¸…é™¤é”æ‹¥æœ‰è€…æ ‡è¯?/span>
26
}
27
setState(c); //讄¡½®åŠ é”状æ€?/span>
28
return free;
29
}
30
31
32
/** *//**
33
* Wakes up node's successor, if one exists.
34
*
35
* @param node the node
36
*/
37
private void unparkSuccessor(Node node)
{
38
/**//*
39
* Try to clear status in anticipation of signalling. It is
40
* OK if this fails or if status is changed by waiting thread.
41
*/
42
compareAndSetWaitStatus(node, Node.SIGNAL, 0); //清除头节点signal状�/span>
43
44
/**//*
45
* Thread to unpark is held in successor, which is normally
46
* just the next node. But if cancelled or apparently null,
47
* traverse backwards from tail to find the actual
48
* non-cancelled successor.
49
*/
50
Node s = node.next;
51
if (s == null || s.waitStatus > 0)
{ //½{‰å¾…队列唤醒的竞争满‘³FIFOåQŒæœ¬ŒDµä»£ç ä¸»è¦æ˜¯å¯ÀL‰¾æœ€é 近头节点的åQŒä¸”waitStatus为signalã€condition的链表节ç‚?/span>
52
s = null;
53
for (Node t = tail; t != null && t != node; t = t.prev)
54
if (t.waitStatus <= 0)
55
s = t;
56
}
57
if (s != null)
58
LockSupport.unpark(s.thread);
59
}

]]>