CoundDownLatch/CyclicBarrier/Semaphore使用过吗
CountDownLatch
主要有两个方法,当一个或者多个线程调用await方法时,调用线程会被阻塞。
其他线程调用countDown方法会将计数器减一(调用countDown方法的线程不会阻塞)
当计数器的值变为零时,因调用await方法被阻塞的线程会被唤醒,继续执行
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName());
}, CountryEnum.forEach_CountryEnum(i).getMsg()).start();
}
countDownLatch.await();
System.out.println("**********秦统一华夏");
}
}
enum CountryEnum{
one(1,"齐国"),two(2,"楚国"),three(3,"燕国"),four(4,"赵国"),five(5,"魏国"),six(6,"韩国");
private Integer code;
private String msg;
public Integer getCode(){
return this.code;
}
public String getMsg(){
return this.msg;
}
CountryEnum(Integer code,String msg){
this.code= code;
this.msg = msg;
}
public static CountryEnum forEach_CountryEnum(Integer index){
for (CountryEnum value : CountryEnum.values()) {
if (value.code == index){
return value;
}
}
return null;
}
}
CyclicBarrier
CyclicBarrier的字面意思是可循环(Cyclic)使用的屏障(Barrier)。它要做的事情是,让一组线程到达一个屏障(也可以叫通同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续干活,线程进入屏障通过CyclicBarrier的await方法。
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{ System.out.println("************召唤神龙"); });
for (int i = 0; i < 7; i++) {
int finalI = i;
new Thread(()->{
System.out.println(String.format("第%d颗龙珠", finalI +1));
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
Semaphore
信号量主要用于两个目的,一个时用于多个资源的互斥使用,另一个用于并发线程数的控制
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(3);
} catch (Exception e) {
e.printStackTrace();
}finally {
semaphore.release();
}
System.out.println(Thread.currentThread().getName()+" 停了3秒离开车位");
},String.valueOf(i)).start();
}