1+ package java0 .conc0302 .threadpool ;
2+
3+ import java .util .concurrent .TimeUnit ;
4+ import java .util .concurrent .locks .AbstractQueuedSynchronizer ;
5+ import java .util .concurrent .locks .Condition ;
6+ import java .util .concurrent .locks .Lock ;
7+
8+ class Mutex implements Lock {
9+ // 静态内部类,自定义同步器
10+ private static class Sync extends AbstractQueuedSynchronizer {
11+ // 是否处于占用状态
12+ @ Override
13+ protected boolean isHeldExclusively () {
14+ return getState () == 1 ;
15+ }
16+
17+ // 当状态为0的时候获取锁
18+ @ Override
19+ public boolean tryAcquire (int acquires ) {
20+ if (compareAndSetState (0 , 1 )) {
21+ setExclusiveOwnerThread (Thread .currentThread ());
22+ return true ;
23+ }
24+ return false ;
25+ }
26+
27+ // 释放锁,将状态设置为0
28+ @ Override
29+ protected boolean tryRelease (int releases ) {
30+ if (getState () == 0 ) throw new IllegalMonitorStateException ();
31+ setExclusiveOwnerThread (null );
32+ setState (0 );
33+ return true ;
34+ }
35+
36+ // 返回一个Condition,每个condition都包含了一个condition队列
37+ Condition newCondition () {
38+ return new ConditionObject ();
39+ }
40+ }
41+
42+ // 仅需要将操作代理到Sync上即可
43+ private final Sync sync = new Sync ();
44+
45+ @ Override
46+ public void lock () {
47+ sync .acquire (1 );
48+ }
49+
50+ @ Override
51+ public boolean tryLock () {
52+ return sync .tryAcquire (1 );
53+ }
54+
55+ @ Override
56+ public void unlock () {
57+ sync .release (1 );
58+ }
59+
60+ @ Override
61+ public Condition newCondition () {
62+ return sync .newCondition ();
63+ }
64+
65+ public boolean isLocked () {
66+ return sync .isHeldExclusively ();
67+ }
68+
69+ public boolean hasQueuedThreads () {
70+ return sync .hasQueuedThreads ();
71+ }
72+
73+ @ Override
74+ public void lockInterruptibly () throws InterruptedException {
75+ sync .acquireInterruptibly (1 );
76+ }
77+
78+ @ Override
79+ public boolean tryLock (long timeout , TimeUnit unit ) throws InterruptedException {
80+ return sync .tryAcquireNanos (1 , unit .toNanos (timeout ));
81+ }
82+ }
0 commit comments