CountDownLatch类

CountDownLatch类是一个“减法计数器”,允许一个线程或多个线程等待直到在其它线程执行完成才执行,如全部人离场才能关门:

  1. public class CountDownLatchTest {
  2. public static void main(String[] args) {
  3. CountDownLatch countDownLatch=new CountDownLatch(6);
  4. for (int i = 0; i < 6; i++) {
  5. new Thread(() -> {
  6. System.out.println(Thread.currentThread().getName() + " 离开了房间");
  7. countDownLatch.countDown();
  8. }, String.valueOf(i + 1)).start();
  9. }
  10. try {
  11. //等待计数器归零,才继续往下执行
  12. countDownLatch.await();
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }
  16. System.out.println("close the door!");
  17. }
  18. }

image.png

CyclicBarrier类

CyclicBarrier类相当于一个“加法计数器”,是允许一组线程全部等待彼此达到共同屏障点的同步辅助,如集齐七颗龙珠召唤神龙:

public class CyclicBarrierTest {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
            System.out.println("召唤神龙!");
        });
        for (int i = 0; i < 7; i++) {
            final int temp = i + 1;
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "收集了第" + temp + "颗龙珠");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }, "线程" + String.valueOf(i + 1)).start();
        }
    }
}

image.png

Semaphore类

Semaphore类是一个计数信号量,用于限制线程的通行流量,如6辆车却只有3个车位,这时候只能限流停车:

public class SemaphoreTest {
    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() + "抢到了车位");
                    //模拟停车时间
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + "离开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //释放通行证
                    semaphore.release();
                }
            }, "线程" + String.valueOf(i + 1)).start();
        }
    }
}

image.png