zoukankan      html  css  js  c++  java
  • countdownlatch+cyclicbarrier+semphore

    countdown

    class q{
        public static void main(String[] args) throws InterruptedException {
            CountDownLatch countDownLatch = new CountDownLatch(5);
            for (int i = 0; i < 5; i++) {
                //开启线程
                new Thread(()->{
                    System.out.println(Thread.currentThread().getName()+"就位");
                    countDownLatch.countDown();
                    System.out.println(Thread.currentThread().getName()+"溜了");
                }).start();
            }
            countDownLatch.await();
            System.out.println("开团");
        }
    }
    

    在countdown只是传递信号,没有约束力

    cyclicbarrier

    class W{
        public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
            //自带了runnable
            CyclicBarrier cyclicBarrier = new CyclicBarrier(5,
                    ()-> System.out.println("666开团"));
            for (int i = 0; i < 5; i++) {
                //开启线程
                new Thread(()->{
                    System.out.println(Thread.currentThread().getName()+"就位");
                    try {
                        cyclicBarrier.await();
                        System.out.println(Thread.currentThread().getName()+"溜了");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
            System.out.println("开团");
        }
    }
    

    这个是有约束了,await就等到集齐,才可以往下走

    sempaphore

    class cc{
        public static void main(String[] args) {
            Semaphore semaphore = new Semaphore(3);
            for (int i = 0; i < 6; i++) {
                new Thread(()->{
                    try {
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName()+"抢到女人了");
                        Thread.sleep(11);
                        System.out.println("离开");
                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ;
                }).start();
            }
        }
    }
    

    很方便,适用于多个共享资源

  • 相关阅读:
    多线程-工作组模式
    iOS端架构、基本组成与使用说明
    iOS,Core Animation--负责视图的复合功能
    Container Views
    IOS UIView 01-View开始深入 绘制像素到屏幕上
    View Programming Guide for iOS
    UI绘图与信息、样式
    iOS绘图框架CoreGraphics分析
    iOS开发系列--打造自己的“美图秀秀”
    Array与NSArray关系
  • 原文地址:https://www.cnblogs.com/purexww/p/15248841.html
Copyright © 2011-2022 走看看