zoukankan      html  css  js  c++  java
  • Java并发编程-闭锁

    闭锁是一种同步器 ( Synchronizer ),它可以延迟线程的进度直到线程到达终止状态,CountDownLatch是一个灵活的闭锁实现:
    1)允许一个或多个线程等待一个事件集的发生,闭锁的状态包括一个计数器,初始化为一个正数,用来实现需要等待的事件数。
    2)countDown对计数器做减操作,表示一个事件已经发生了,而await方法等待计数器达到0,此时所有需要等待的事件都已经发生。
    3)如果计数器的入口时值为非零,await会一直阻塞直到计数器为0,或等待线程中断及超时。

    public long timeTasks(int nThreads, final Runnable task)
                throws InterruptedException {
            final CountDownLatch startGate = new CountDownLatch(1);
            final CountDownLatch endGate = new CountDownLatch(nThreads);
            for (int i = 0; i < nThreads; i++) {
                Thread t = new Thread() {
                    public void run() {
                        try {
                            startGate.await();
                            try {
                                task.run();
                            } finally {
                                endGate.countDown();
                            }
                        } catch (InterruptedException ignored) {
                        }
                    }
                };
                t.start();
            }
            long start = System.nanoTime();
            startGate.countDown();
            endGate.await();
            long end = System.nanoTime();
            return end - start;
        }
    

    Latch - A latch is a synchronizer that can delay the progress of threads until it reaches its terminal state. A latch acts as a gate: until the latch reaches the terminal state the gate is closed and no thread can pass, and in the terminal state the gate opens, allowing all threads to pass. Once the latch reaches the terminal state, it cannot change state again, so it remains open forever. Latches can be used to ensure that certain activities do not proceed until other one-time activities complete。

  • 相关阅读:
    第12课 计算器核心解析算法(上)
    第11课 Qt中的字符串类
    第10课 初探 Qt 中的消息处理
    第9课 计算器界面代码重构
    第8课 启航!第一个应用实例
    第7课 Qt中的坐标系统
    第6课 窗口部件及窗口类型
    第5课 Qt Creator工程介绍
    第4课 Hello QT
    给Linux内核增加一个系统调用的方法(转)
  • 原文地址:https://www.cnblogs.com/suxuan/p/4948750.html
Copyright © 2011-2022 走看看