常用辅助类

计数器

减法计数器 CountDownLatch
public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
        //计数器,倒计时,递减操作
        CountDownLatch countDownLatch = new CountDownLatch(10);

        for (int i = 1; i <= 10; i++){
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+" Go Out!");
                countDownLatch.countDown();//减一
            },String.valueOf(i)).start();
        }
        //等待计数器归零,然后再向下执行。
        countDownLatch.await();

        System.out.println("Close Door");
    }
}
加法计数器 CyclicBarrier
public class Demo03 {
    public static void main(String[] args) {
        /**
         * 集齐7颗龙珠召唤神龙*/
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
            /*召唤神龙!*/
            System.out.println("出来吧!神龙!!!!");
        });

        for (int i = 1;i <= 7; i++){
            final int temp = i;
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"收集"+temp+"个龙珠!");

                try {
                    //等待 计数器加到7
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }

    }
}

Semaphore

public class Demo04 {
    public static void main(String[] args) {
        /**
         * 模拟一个抢车位*/
        //Semaphore 信号量 构造默认参数可以认为是给定的线程数量
        //引用场景:限流!
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <= 6; i++){
            new Thread(()->{
                try {
                    //获得,取得
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到车位!");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName()+"离开车位!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    //释放
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}

你可能感兴趣的:(常用辅助类)