[@talishboy][¥20]CountDownLatch 是否可以使用独占锁来实现?
你这个实现针对多个线程调用await情况,无法唤醒所有线程. 不知道理解有没有问题? 我通过模仿ReentrantLock实现了一个独占访问的代码
public class MyCountDownLatch {
private final Sync sync ;
public MyCountDownLatch(int state) {
sync = new Sync(state);
}
private static final class Sync extends AbstractQueuedSynchronizer {
Sync(int state) {
setState(state);
}
@Override
protected boolean tryAcquire(int arg) {
return getState() == 0;
}
@Override
protected boolean tryRelease(int arg) {
for (; ; ) {
int c = getState();
if (c == 0)
return true;
int nextc = c - 1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
public void await() {
try {
sync.acquire(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
sync.release(1);
}
}
public void countDown() {
sync.release(1);
}
public static void main(String... args) throws InterruptedException {
MyCountDownLatch countDownLatch = new MyCountDownLatch(5);
Thread thread1 = new Thread() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+':----->1 before await()');
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+':----->1');
}
};
Thread thread2 = new Thread() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+':----->2 before await()');
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+':----->2');
}
};
thread1.start();
thread2.start();
Thread.sleep(100);
System.out.println('start');
countDownLatch.countDown();
countDownLatch.countDown();
countDownLatch.countDown();
countDownLatch.countDown();
countDownLatch.countDown();
}
}
赞0
踩0