CountDownLatch
- countDownLatch这个类是通过一个计数器来实现的,计数器的初始值是线程的数量。当一个线程执行完毕后,计数器减一,当计数器的值为0时,表示所有线程都执行完毕,然后在等待的线程就可以恢复工作了
package com.xiaojie.readwrite.ReadWriteLock;
import jdk.nashorn.internal.objects.annotations.Getter;
import java.util.concurrent.CountDownLatch;
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(()->{
System.out.println(Thread.currentThread().getName()+"国被灭");
countDownLatch.countDown();
},CountryEunm.forEach(i).getRetMesage()).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+"秦国,一统华夏");
}
}
enum CountryEunm{
ONE(1,"齐"),TWO(2,"楚"),THREE(3,"燕"),FOUR(4,"赵"),FIVE(5,"魏"),SIX(6,"韩");
private Integer retCode;
private String retMesage;
public Integer getRetCode() {
return retCode;
}
public String getRetMesage() {
return retMesage;
}
CountryEunm(Integer retCode, String retMesage) {
this.retCode = retCode;
this.retMesage = retMesage;
}
public static CountryEunm forEach(int index){
CountryEunm[] values = CountryEunm.values();
for (CountryEunm value : values) {
if (index==value.getRetCode()){
return value;
}
}
return null;
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5b41225924fe0d6cd88e2c5429ffc701.jpeg#pic_center)
CyclicBarrier
- CyclicBarrier跟上面相反,线程结束加一,加到设置数则执行
package com.xiaojie.readwrite.ReadWriteLock;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("召唤神农");
});
for (int i = 1; i <= 7; i++) {
final int t = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+": "+t+"龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/44cd1931eb2638d49d8c1c020c8abab8.jpeg#pic_center)
Semaphore
- Semaphore可以控制当前访问自身的线程个数,设为1可以退化为synchronized
package com.xiaojie.readwrite.ReadWriteLock;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
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(3);
System.out.println(Thread.currentThread().getName()+"停车3秒后离开");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f7ed58d561880149cfe640bc4782f45e.jpeg#pic_center)