【JAVA学习笔记】CountDownLatch、CyclicBarrier、Semaphore

这三个都是concurrent并发包下面的并发工具类,那么他们有什么区别呢,下面一个个通过比喻梳理

1、Semaphore。

semaphore的应用场景想象成:停车场

如下代码  Semaphore semaphore = new Semaphore(2);也就是说停车场里有2个空位,for循环5次比作有5辆车来停车,开始时 ,最前面的2辆车通过semaphore.acquire();方法获取进入资格,占用车位,后面三辆车调用acquire时发现没有空的车位资源可以给他们,于是等待,当里面的车通过semaphore.release();释放占用的车位资源(开走了),后面的车就按开走几辆进来几辆的原则,使用车位。

public class SemaphoreDemo {

    public static void main(String[] args) {
        System.out.println("Start");
        Semaphore semaphore = new Semaphore(2);
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new SemaphoreWorker(semaphore));
            thread.start();
        }
    }

}

class SemaphoreWorker implements Runnable {
    private String name;
    private Semaphore semaphore;

    public SemaphoreWorker(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            print("is waiting for a permit!");
            semaphore.acquire();
            print("acquired a permit!  executed!");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        } finally {
            print("released a permit!");
            semaphore.release();
        }
    }

    public void print(String msg) {
        if (null == this.name) {
            this.name = Thread.currentThread().getName();
        }
        System.out.println(this.name + "  [" + msg + "]");
    }
}

2、CyclicBarrier

cyclicbarrier的应用场景可以想象成:悟空一行人分头去收集七龙珠,每个人都成功后一起召唤神龙

//这里定义要收集7颗龙珠,--收集完成后--开始线程打印“完成收集”
private static CyclicBarrier cyclicBarrier = new CyclicBarrier(MaxCountDownLatchNumber, new Thread(() -> {
    System.out.println("完成收集");
}));

每个线程收集一颗龙珠,在cyclicBarrier.await()这里等待其他线程,当7个线程全部收集完,并到await这里后,启动新一个线程,打印“完成收集”,之后每个线程打印“成功收集:”

public class CyclicBarrierDemo {

    private static int MaxCountDownLatchNumber = 7;

    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(MaxCountDownLatchNumber, new Thread(() -> {
        System.out.println("完成收集");
    }));

    public static void main(String args[]) {

        for (int i = 1; i <= MaxCountDownLatchNumber; i++) {
            System.out.println("开始收集:" + i);
            int index = i;
            new Thread(() -> {

                System.out.println("已收集:" + index);
                try {
                    cyclicBarrier.await();
                    System.out.println("成功收集:" + index);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();

        }
        System.out.println("222");
    }
}

3、CountDownLatch
CountDownLatch的应用场景想象成:我要收集龙珠,派了7个小弟(线程)去,我在countDownLatch.await()这里等待。每个小弟收集成功就countDownLatch.countDown()一下,我收到7个countDown后,完成收集。

 

public class CountDownLatchDemo {

    public static void main(String args[]) throws Exception {
        int MaxCountDownLatchNumber = 7;

        final CountDownLatch countDownLatch = new CountDownLatch(7);
        for (int i = 1; i <= MaxCountDownLatchNumber; i++) {
            System.out.println("开始收集:" + i);
            int index = i;
            new Thread(() -> {
                try {
                    System.out.println("已收集:" + index);
                    countDownLatch.countDown();
                    System.out.println("成功----------------:" + index);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
        countDownLatch.await(10000, TimeUnit.MILLISECONDS);
        System.out.println("完成收集");
    }
}

猜你喜欢

转载自blog.csdn.net/u010530712/article/details/85334351
今日推荐