Repository navigation
Expand file tree
/
Copy pathBooleanLock.java
More file actions
74 lines (62 loc) · 2.15 KB
/
Copy pathBooleanLock.java
File metadata and controls
74 lines (62 loc) · 2.15 KB
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
68
69
70
71
72
73
74
package com.concurrent.thread.lock;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* 自定义显示锁
*/
public class BooleanLock implements Lock {
private volatile boolean isLocked;
public BooleanLock() {
this.isLocked = false;
}
private Collection<Thread> blockedThread = new ArrayList<>();
private Thread currentThread;
@Override
public synchronized void lock() throws InterruptedException {
while (isLocked) {
blockedThread.add(Thread.currentThread());
this.wait();
}
System.out.println(Thread.currentThread().getName() + " -> locked");
blockedThread.remove(Thread.currentThread());
this.isLocked = true;
this.currentThread = Thread.currentThread();
}
@Override
public synchronized void lock(long millis) throws InterruptedException, TimeOutException {
if (millis <= 0)
lock();
long hasRemaining = millis;
long endTime = System.currentTimeMillis() + millis;
while (isLocked) {
//在超时时间内没有获取到锁抛出超时异常
if (hasRemaining <= 0)
throw new TimeOutException("get lock timeout");
blockedThread.add(Thread.currentThread());
this.wait(millis);
hasRemaining = endTime - System.currentTimeMillis();
}
blockedThread.remove(Thread.currentThread());
this.isLocked = true;
this.currentThread = Thread.currentThread();
}
@Override
public synchronized void unlock() throws InterruptedException {
//只有当前线程自己可以解锁
if (currentThread == Thread.currentThread()) {
System.out.println(Thread.currentThread().getName() + " -> release");
this.notifyAll();
this.isLocked = false;
}
}
@Override
public Collection<Thread> getBlockedThread() {
//expose readOnly blocked Collection
return Collections.unmodifiableCollection(blockedThread);
}
@Override
public int getBlockedSize() {
return blockedThread.size();
}
}