JUC详解 -> 常用辅助类(必会)
1. CountDownLatch
减法计数器
代码测试:
import java.util.concurrent.CountDownLatch;
//减法计数器
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//倒计时,总数是6
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6 ; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+" go out");
countDownLatch.countDown(); //-1
},String.valueOf(i)).start();
}
countDownLatch.await(); //等待计数器归零,然后再向下执行
System.out.println("Close door");
}
}
原理:
countDownLatch.countDown();
countDownLatch.await();
每次有线程调用countDown()数量减一,假设计数器变为0,await()就会被唤醒,继续执行
2. CyclicBarrier
加法计数器
代码测试
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.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 temp = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"收集了"+temp+"个龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
3. Semaphore
信号量
- 抢车位:6个车3个车位 123 456 --> 124 56 --> 524 6
代码测试:
package com.anobabe.add;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
public static void main(String[] args) {
//参数可以理解为线程数量; 限流!
//3个停车位
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <= 6 ; i++) {
new Thread(()->{
//acquire() 得到
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 {
//release() 释放
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
- 原理:
semaphore.acquire()
获得,假如已经满了,等待被释放为止semaphore.release()
释放,会将当前的信号量释放+1,然后唤醒等待的线程
- 作用:
- 多个共享资源互斥的使用!
- 并发限流!控制最大的线程数!