【发布时间】:2018-11-20 12:48:25
【问题描述】:
JDK1.8的源码是通过AQS共享锁实现的,使用共享锁有哪些注意事项?为什么不使用排他锁?下面附上我的排他锁实现的代码:
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");
}
}
【问题讨论】:
-
你没有附加任何代码
-
请提供您代码的相关部分。添加一个Minimal, Complete, and Verifiable example,包括正确的示例输入/输出数据。
-
错误 404:找不到代码。
-
我已经提交了我的代码。谢谢
标签: java concurrency java.util.concurrent