CountDownLatch 可以使用独占锁实现吗?
Can CountDownLatch be implemented using an exclusive lock?
JDK1.8的源码是AQS共享实现的lock.What使用共享锁有什么注意事项吗?为什么不使用独占锁呢?下面附上我的排他锁实现的代码:
public class MyCountDownLatch {
private static final class Sync extends AbstractQueuedSynchronizer {
Sync(int count) {
setState(count);
}
int getCount() {
return getState();
}
protected boolean tryAcquire(int acquires) {
return (getState() == 0) ? true :false;
}
protected boolean tryRelease(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
private final MyCountDownLatch.Sync sync;
public MyCountDownLatch(int count) {
this.sync = new MyCountDownLatch.Sync(count);
}
public void await() throws InterruptedException {
sync.acquireInterruptibly(1);
}
public void countDown() {
sync.release(1);
}
public static void main(String[] args) throws InterruptedException {
MyCountDownLatch myCountDownLatch = new MyCountDownLatch(5);
for(int i=0;i<5;i++){
new Thread(()-> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"start");
myCountDownLatch.countDown();
}).start();
}
myCountDownLatch.await();
System.out.println("finished");
}
}
嗯,shared lock
意味着,您可以有超过 1 个线程等待完成。如果您使用 exclusive lock
实现它,那么您将只能等待 1 个线程。
JDK1.8的源码是AQS共享实现的lock.What使用共享锁有什么注意事项吗?为什么不使用独占锁呢?下面附上我的排他锁实现的代码:
public class MyCountDownLatch {
private static final class Sync extends AbstractQueuedSynchronizer {
Sync(int count) {
setState(count);
}
int getCount() {
return getState();
}
protected boolean tryAcquire(int acquires) {
return (getState() == 0) ? true :false;
}
protected boolean tryRelease(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
private final MyCountDownLatch.Sync sync;
public MyCountDownLatch(int count) {
this.sync = new MyCountDownLatch.Sync(count);
}
public void await() throws InterruptedException {
sync.acquireInterruptibly(1);
}
public void countDown() {
sync.release(1);
}
public static void main(String[] args) throws InterruptedException {
MyCountDownLatch myCountDownLatch = new MyCountDownLatch(5);
for(int i=0;i<5;i++){
new Thread(()-> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"start");
myCountDownLatch.countDown();
}).start();
}
myCountDownLatch.await();
System.out.println("finished");
}
}
嗯,shared lock
意味着,您可以有超过 1 个线程等待完成。如果您使用 exclusive lock
实现它,那么您将只能等待 1 个线程。