码迷,mamicode.com
首页 > 其他好文 > 详细

CountDownLatch、CyclicBarrier、Semaphore使用例子

时间:2021-04-21 12:21:06      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:getname   throw   row   inter   finally   rgs   线程   exce   启动   

都是JUC并发包下的类

CountDownLatch:倒计时,countDown每次减少,await控制达到倒计时要求值

//下自习离开案例,班长必须最后走
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        general();
    }

    public static void general(){
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName()+"\t上完自习,离开教室");
            }, "Thread-->"+i).start();
        }
        while (Thread.activeCount()>2){
            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
        }
        System.out.println(Thread.currentThread().getName()+"\t=====班长最后关门走人");
    }

}

CyclicBarrier:正计时,到达某个数时,被约束线程才能启动

//七颗龙珠集齐才能召唤神龙
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        cyclicBarrierTest();
    }

    public static void cyclicBarrierTest() {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
            System.out.println("====召唤神龙=====");
        });
        for (int i = 1; i <= 7; i++) {
            final int tempInt = i;
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "\t收集到第" + tempInt + "颗龙珠");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }, "" + i).start();
        }
    }
}

Semaphore:信号灯,有伸缩性,坑位在不停占用和释放

public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);//模拟三个停车位
        for (int i = 1; i <= 6; i++) {//模拟6部汽车
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "\t抢到车位");
                    try {
                        TimeUnit.SECONDS.sleep(3);//停车3s
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t停车3s后离开车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }, "Car " + i).start();
        }
    }
}

CountDownLatch、CyclicBarrier、Semaphore使用例子

标签:getname   throw   row   inter   finally   rgs   线程   exce   启动   

原文地址:https://www.cnblogs.com/crisliu/p/14678807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!