一、CountDownLatch类【减法计数器】
1. 介绍

2. 代码演示
package supportclass;
import java.util.concurrent.CountDownLatch;
public class Test01 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " Go out");
countDownLatch.countDown();
}, String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + " Close door");
}
}
- 每次有线程调用countDown()方法时,数量减去1,直到计数器的数量变为0,countDownLatch.await()就会被唤醒,程序继续往下面执行,否则程序会阻塞
二、CyclicBarrier类【加法计数器】
1. 介绍

2. 代码演示
package supportclass;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
public class Test02 {
public static void main(String[] args) throws InterruptedException {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("线程:" + Thread.currentThread().getName() + " => 召唤神龙成功!");
});
for (int i = 1; i <= 7; i++) {
final int temp = i;
new Thread(() -> {
System.out.println("线程:" + Thread.currentThread().getName() + " => 收集【" + temp + "】龙珠!");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
TimeUnit.SECONDS.sleep(2);
System.out.println("线程:" + Thread.currentThread().getName() + " => 退出!");
}
}
三、Samephore类【信号量】
1. 介绍

- semaphore.acquire()
① 获得许可证,如果许可证被其他线程获取了,该方法就会等待,直到其他线程释放许可证为止 - semaphore.release()
① 释放许可证,会将当前信号量释放,然后信号量+1,唤醒其他等待的线程 - Semaphore类作用
① 多个共享资源互斥
② 并发限流,控制最大线程数量
2. 代码演示
package supportclass;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class Test03 {
public static void main(String[] args) {
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();
}
}
}