zoukankan      html  css  js  c++  java
  • java CountDownLatch

    Listing 6-1. Using a Countdown Latch to Trigger a Coordinated Start
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    public class CountDownLatchDemo
    {
        final static int NTHREADS = 3;
        public static void main(String[] args)
        {
            final CountDownLatch startSignal = new CountDownLatch(1);
            final CountDownLatch doneSignal = new CountDownLatch(NTHREADS);
            Runnable r = new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        report("entered run()");
                        startSignal.await(); // wait until told to ...
                        report("doing work"); // ... proceed
                        Thread.sleep((int) (Math.random() * 1000));
                        doneSignal.countDown(); // reduce count on which
                        // main thread is ...
                    } // waiting
                    catch (InterruptedException ie)
                    {
                    System.err.println(ie);
                    }
                }
    
                void report(String s)
                {
                System.out.println(System.currentTimeMillis() +
                ": " + Thread.currentThread() +            ": " + s);
                }
            };
            
            ExecutorService executor = Executors.newFixedThreadPool(NTHREADS);
            for (int i = 0; i < NTHREADS; i++)
                executor.execute(r);
                try
                {
                    System.out.println("main thread doing something");
                    Thread.sleep(1000); // sleep for 1 second
                    startSignal.countDown(); // let all threads proceed
                    System.out.println("main thread doing something else");
                    doneSignal.await(); // wait for all threads to finish
                    executor.shutdownNow();
                }
                catch (InterruptedException ie)
                {
                System.err.println(ie);
                }
        }
    }
  • 相关阅读:
    零知识证明入门
    Vue入门语法(二)表单,组件,路由和ajax
    Vue入门语法(一)
    okexchain整体架构分析
    写了个unsigned Tx生成二维码的web站点
    metamusk与web3相关资料
    QRCode.js:使用 JavaScript 生成二维码
    js工程安装,发布等命令
    C语言学习笔记-9.结构体
    C语言学习笔记-8.指针
  • 原文地址:https://www.cnblogs.com/rojas/p/5367008.html
Copyright © 2011-2022 走看看