CountDownLatch:让一些线程阻塞直到另一些线程完成一系列操作后才被唤醒
CountDownLatch主要有两个方法,当一个或多个线程调用await()方法时,调用线程会被阻塞。其它线程调用countDown()方法会将计数器减1(调用countDown方法的线程不会阻塞),当计数器的值变为零时,因调用await方法被阻塞的线程会被唤醒,继续执行。
//这个枚举一定要学会,项目中常用
public enum CountryEnum{
ONE(1, "齐"),TWO(2, "楚"),THREE(3, "燕"),FOUR(4, "赵"),FIVE(5, "韩"),SIX(6, "魏");
@Getter private Integer retCode;
@Getter private String retMessage;
countryEnum(Integer retCode, String retMessage){
this.retCode = retCode;
this.retMessage = retMessage;
}
public static CountryEnum forEach_CountryEnum(int index){
CountryEnum[] myArray = CountryEnum.values();
for(CountryEnum element : myArray){
if(index == element.getRetCode()){
return element;
}
}
return null;
}
}
public class CountDownLatchDemo{
public static void main(String[] args) throws Exception{
CountDownLatch counDownLatch = new CountDownLatch(6);
for(int i = 1; i <= 6; i++){
new Thread(() -> {
System.out.println(Thread.currentThread.getName()+"\t 国,被灭");
countDownLatch.countDown();
},CountryEnum.forEach_CountryEnum(i).getRetMessage()).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread.getName()+"\t 秦帝国,一统华夏");
System.out.println(CountryEnum.ONE);
System.out.println(CountryEnum.ONE.getRetCode());
System.out.println(CountryEnum.ONE.getRetMessage());
}
public static void closeDoor() throws InterruptedException{
CountDownLatch counDownLatch = new CountDownLatch(6);
for(int i = 1; i <= 6; i++){
new Thread(() -> {
System.out.println(Thread.currentThread.getName()+"\t 上完自习,离开教室");
countDownLatch.countDown();
},String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread.getName()+"\t 班长最后关门走人");
}
}
CyclicBarrier:字面意思是可循环(Cyclic)使用的屏障(Barrier)。它要做的事情是,让一组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续干活,线程进入屏障通过CyclicBarrier的await()方法
public class CyclicBarrierDemo{
public static void main(String[] args){
//CyclicBarrier(int parties, Runnable barrierAction)
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("****召唤神龙");
});
for(int i = 1; i <= 7 ; i++){
final int tempInt = i;
new Thread(() -> {
System.out.println(Thread.currentThread().getName()+"\t 收集到第:"+tempInt+"龙珠");
try{
cyclicBarrier.await();
}catch(InterrupttedException e){
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
Semaphone:信号量主要用于两个目的,一个是用于多个共享资源的互斥使用,另一个用于并发线程数的控制
public class SemaphoreDemo{
public static void main(String[] args){
Semaphore semaphore = new Semaphore(3);//模拟3个停车位
for(int i = 1; i <= 6; i++){//模拟6部汽车
new Thread(() -> {
try{
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"\t 抢到车位");
try{//暂停一会儿线程
TimeUnit.SECONDS.sleep(3);}catch(InterruptedException e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"\t 停车3秒后离开车位");
}catch(InterrupttedException e){
e.printStackTrace();
}finally{
}
},String.valueOf(i)).start();
}
}
}