Created
May 18, 2016 01:27
-
-
Save liuzhengyang/aa7cb450e91057d36bc7ee72c6a2ba11 to your computer and use it in GitHub Desktop.
count down latch using aqs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private final class Sync extends AbstractQueuedSynchronizer { | |
private int count; | |
public Sync(int count) { | |
this.count = count; | |
} | |
@Override | |
protected int tryAcquireShared(int arg) { | |
return (getState() == 0 ? 1 : -1); | |
} | |
@Override | |
protected boolean tryReleaseShared(int arg) { | |
for (;;) { | |
int c = getState(); | |
if (c == 0) { | |
return false; | |
} | |
int nextc = c - 1; | |
if (compareAndSetState(c, nextc)) { | |
return nextc == 0; | |
} | |
} | |
} | |
} | |
private Sync sync = null; | |
private int count; | |
public MyCountDown(int count) { | |
this.sync = new Sync(count); | |
} | |
public void await() throws InterruptedException { | |
sync.acquireSharedInterruptibly(1); | |
} | |
public void countDown() { | |
sync.releaseShared(1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment