• Java深入学习08:CountDownLatch应用


    Java深入学习08:CountDownLatch应用

    一、CountDownLatch是什么

       A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

      CountDownLatch是一个同步助手,它允许一个或多个线程在在其他线程中执行的一组操作完成前,一直处于等待状态。

    二、案例

    public class CountDownLatchTest {
        public static void main(String[] args) {
            CountDownLatch latch = new CountDownLatch(100);
            CountDownLatchThread th = new CountDownLatchThread(latch);
            long start = System.currentTimeMillis();
            for(int i = 0; i< 100; i++){
                new Thread(th).start();
            }
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            long end = System.currentTimeMillis();
            System.out.println("一共花费:" + (end - start) + " 毫秒");
    
        }
    }
    class CountDownLatchThread implements Runnable{
        private CountDownLatch latch ;
        public CountDownLatchThread(CountDownLatch latch){
            this.latch = latch;
        }
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName()+"完成任务");
            } finally {
                //计数减1
                latch.countDown();
            }
        }
    }

     日志输出

    Thread-0完成任务
    Thread-5完成任务
    Thread-4完成任务
    Thread-3完成任务
    Thread-2完成任务
    Thread-1完成任务
    .......
    Thread-97完成任务
    Thread-99完成任务
    一共花费:11 毫秒
    
    Process finished with exit code 0

    三、CountDownLatch主要方法   

       //计数
       //Decrements the count of the latch, releasing all waiting threads if  the count reaches zero.
        public void countDown() {
            sync.releaseShared(1);
        }
      
        //等待
       //the current thread to wait until the latch has counted down to zero
        public void await() throws InterruptedException {
            sync.acquireSharedInterruptibly(1);
        }

    四、应用场景

      当一个主任务中,有多个子任务可以同时进行(多个线程),最有有一个或多个子任务,需要在前面的任务全部完成后才可以执行,那么就可以用CountDownLatch实现"在前面的任务全部完成后才可以执行"

  • 相关阅读:
    什么是一阶矩和二阶矩?
    [Pytorch]基于混和精度的模型加速
    Pytorch: 命名实体识别: BertForTokenClassification/pytorch-crf
    ipykernel_launcher.py: error: unrecognized arguments: -f /Users/apple/Library/Jupyter/runtime/kernel
    pytorch中查看gpu信息
    NLP突破性成果 BERT 模型详细解读 bert参数微调
    os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "0"
    禁用gpu首选
    Tensorflow中tf.ConfigProto()详解
    python命令之m参数 局域网传输
  • 原文地址:https://www.cnblogs.com/wobuchifanqie/p/12512337.html
Copyright © 2020-2023  润新知