zoukankan      html  css  js  c++  java
  • 闭锁(CountDownLatch)

    package japan.example.test;
    
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    
    public class CountDownLatchTest {
    
        public static void main(String[] args) throws Exception {
    
            CountDownLatchTest test = new CountDownLatchTest();
            test.test();
        }
    
        public void test() throws InterruptedException {
            int nthread = 5;
            ExecutorService service = Executors.newFixedThreadPool(nthread);
    
            CountDownLatch latch = new CountDownLatch(nthread);
    
            for (int i = 0; i < nthread; i++) {
                service.execute(new Runner(latch));
            }
    
            latch.await();
    
            service.shutdown();
            while (!service.isTerminated()) {
                try {
                    // 用于等待子线程结束,再继续执行下面的代码
                    service.awaitTermination(5, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
        }
    
    }
    
    class Runner implements Runnable {
    
        CountDownLatch latch;
    
        Runner(CountDownLatch latch) {
            this.latch = latch;
        }
    
        @Override
        public void run() {
            try {
                // dosomething
                System.err.println("say hello!");
            } finally {
                latch.countDown();
            }
        }
    
    }
  • 相关阅读:
    Python3---常见函数---super()
    Python3---常见函数---type()
    Python3---面对对象
    Python3---BeautifulSoup---节点选择器
    Python3---Beautiful Soup
    0X01应用程序黑客技术
    Python3---标准库---re
    (trie) UVA
    (trie)UVALive
    (平方分割)POJ 2104 K-th Number
  • 原文地址:https://www.cnblogs.com/jpit/p/8444826.html
Copyright © 2011-2022 走看看