CountDownLatch
减法计数器
// 计数器
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
// 计数器总数是6(传递参数定义总数)
// 必须要执行任务的时候使用
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(()->{
System.out.println("Go Out");
countDownLatch.countDown(); // 计数器 -1
}).start();
}
// 等待计数器归 0 才继续往下执行
countDownLatch.await();
System.out.println("Close Door");
}
}
countDownLatch.countDown(); // 计数器数量-1
countDownLatch.await(); // 等待计数器归 0 ,在向下执行
每次有线程调用countDown(); 计数器就会-1 ,直到计数器变为0 ,await();就会被唤醒,继续执行
CyclicBarrier
加法计数器
// 加法计数器
public class CyclicBarrierDemo {
public static void main(String[] args) {
// 计数器到达7 执行线程
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("集齐七颗龙珠");
});
for (int i = 1; i <= 7; i++) {
final int tempI = i;
new Thread(()->{
System.out.println("收集了:" + tempI + "颗粒");
try {
cyclicBarrier.await(); // 等待
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
Semaphore
信号量
// 信号量
public class SemaphoreDemo {
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();
}
}
}
semaphore.aquire(); // 获取信号量,如果满了,需要等待,等待被释放
semaphore.release(); // 释放,将当前信号量-1 然后唤醒等待线程
作用: 多个共享资源互斥的使用!并发限流,控制最大的线程