文章目录
1.CountDownLatch
某个线程等待其他线程执行完毕之后在执行的工具 ,做减法 减到0 再执行
public static void main(String[] args) throws Exception{
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i <6 ; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"\t 上完自习 离开教室");
countDownLatch.countDown();
},String.valueOf(i)).start();
}
countDownLatch.await(); // 让计数的值减到0 才可以继续往下执行
System.out.println("班长锁门,最后离开教室");
}
输出结果如下:
3 上完自习 离开教室
2 上完自习 离开教室
1 上完自习 离开教室
5 上完自习 离开教室
6 上完自习 离开教室
4 上完自习 离开教室
班长锁门,最后离开教室
枚举可以当作小型数据库来使用,很实用
public class CDLM {
public static void main(String[] args) throws Exception{
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <=6 ; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"\t 国被灭");
countDownLatch.countDown();
},CountryEnum.forEachEnum(i).getRetMessage()).start();
}
countDownLatch.await();
System.out.println(" 秦国实现大一统 ");
}
}
public enum CountryEnum {
ONE(1,"齐"),TWO(2,"楚"),THREE(3,"燕"),FOUR(4,"赵"),FIVE(5,"魏"),SIX(6,"韩");
@Data private Integer retCode;
@Data private String retMessage;
public static CountryEnum forEachEnum(int index){
CountryEnum [] countryEnums = CountryEnum.values();
for (CountryEnum cEnum:countryEnums) {
if (index==cEnum.getRetCode())
return cEnum;
}
return null;
}
} `
CyclicBarrier
参考博文
做加法,加到规定数目才可以执行程序
线程在countDown()之后,会继续执行自己的任务,而CyclicBarrier会在所有线程任务结束之后,才会进行后续任务,。
CountDownLatch强调一个线程等多个线程完成某件事情。CyclicBarrier是多个线程互等,等大家都完成。
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println(" 召唤神龙 ");
});
for (int i = 1; i <=7 ; i++) {
final int trmp = i ;
new Thread(()->{
System.out.println("收集到第"+ trmp +"颗龙珠");
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
},trmp+"").start();
}
}
结果如下:
收集到第1颗龙珠
收集到第3颗龙珠
收集到第4颗龙珠
收集到第2颗龙珠
收集到第5颗龙珠
收集到第6颗龙珠
收集到第7颗龙珠
召唤神龙
CyclicBarrier和CountDownLatch的区别:
1.CountDownLatch减计数,CyclicBarrier加计数。
2.CountDownLatch是一次性的,CyclicBarrier可以重用。
Semaphore
相关参考文章
参考文章2
Semaphore可以控制某个资源可被同时访问的个数,通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可
多个线程抢夺多个资源 类似于秒杀
public class SemaphoreDemo {
public static void main(String[] args) {
/** 模拟三个停车位 */
Semaphore semaphore = new Semaphore(3);
/** 模拟6 辆车 */
for (int i = 1; i <=6 ; i++) {
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 停车三秒后离开车位 ");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release(); /** 释放资源 */
}
}, String.valueOf(i)).start();
}
}
}