1607616329964517_个人页

个人头像照片 1607616329964517
个人头像照片
0
1
0

个人介绍

暂无个人介绍

擅长的技术

获得更多能力
通用技术能力:

暂时未有相关通用技术能力~

云产品技术能力:

暂时未有相关云产品技术能力~

阿里云技能认证

详细说明
暂无更多信息

2019年07月

正在加载, 请稍后...
暂无更多信息
  • 回答了问题 2019-07-24

    [@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
正在加载, 请稍后...
滑动查看更多
正在加载, 请稍后...
暂无更多信息