CountDownLatch

//CountDownLatch用于同步多个任务,强制他们等待由其他任务执行的一组操作完成。
//其底层是由AQS提供支持
public class CountDownLatch {
    /**
     * Synchronization control For CountDownLatch.
     * Uses AQS state to represent count.
     */
    private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            setState(count);
        }
        //返回当前计数
        int getCount() {
            return getState();
        }
        //试图在共享模式下获取对象状态
        protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }
        // 试图设置状态来反映共享模式下的一个释放
        protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();//获取状态
                if (c == 0)//没有线程占有
                    return false;
                int nextc = c-1;//线程减1
                if (compareAndSetState(c, nextc))//比较并设置
                    return nextc == 0;
            }
        }
    }
    //同步队列
    private final Sync sync;

    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }

    //当前线程在锁存器倒计数至零之前一直等待,除非线程被中断。
    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    public boolean await(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

    //将递减锁存器的计数,如果计数到达零,则释放所有等待的线程 
    public void countDown() {
        sync.releaseShared(1);
    }

    public long getCount() {
        return sync.getCount();
    }

    public String toString() {
        return super.toString() + "[Count = " + sync.getCount() + "]";
    }
}
public class Main {

    static class Runner implements Runnable {

        private CountDownLatch cdlatch;
        private String name;

        public Runner(String name, CountDownLatch cdlatch) {
            this.name = name;
            this.cdlatch = cdlatch;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(100 * (new Random()).nextInt(100));
                System.out.println(name + "出发.");
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
            System.out.println(name + "到达目的地.");
            cdlatch.countDown();
        }
    }

    public static void main(String[] arg) {
        CountDownLatch cdlatch = new CountDownLatch(3);
        Thread t1 = new Thread(new Runner("1号",cdlatch));
        Thread t2 = new Thread(new Runner("2号",cdlatch));
        Thread t3 = new Thread(new Runner("3号",cdlatch));
        t1.start();
        t2.start();
        t3.start();
        try {
            cdlatch.await();
        }catch (InterruptedException ie) {
            ie.printStackTrace();
        }
        System.out.println("finished");
        /*Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {

        }
        scan.close();*/
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值