-
Notifications
You must be signed in to change notification settings - Fork 20
/
SimpleReentrantLock.java
67 lines (56 loc) · 1.53 KB
/
SimpleReentrantLock.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.github.mottox.taomp.concurrent.locks;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.github.mottox.taomp.common.ThreadID;
/**
* 简单的可重入锁。
*/
public class SimpleReentrantLock implements SimpleLock {
private Lock lock;
private Condition condition;
private volatile int owner;
private volatile int holdCount;
public SimpleReentrantLock() {
// 只是借用java.util.concurrent.ReentrantLock来实现互斥。
this.lock = new ReentrantLock();
this.condition = lock.newCondition();
this.owner = -1;
this.holdCount = 0;
}
@Override
public void lock() {
int me = ThreadID.get();
lock.lock();
try {
if (owner == me) {
holdCount++;
return;
}
while (holdCount != 0) {
condition.await();
}
owner = me;
holdCount = 1;
} catch (InterruptedException e) {
// empty
} finally {
lock.unlock();
}
}
@Override
public void unlock() {
lock.lock();
try {
if (holdCount == 0 || owner != ThreadID.get()) {
throw new IllegalMonitorStateException();
}
holdCount--;
if (holdCount == 0) {
condition.signal();
}
} finally {
lock.unlock();
}
}
}