CountDownLatch
//倒计时 减法
//6个学生,班长最后锁门
//当计数器变为0时,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(() -> {
System.out.println(Thread.currentThread().getName()+" 离开教室");
countDownLatch.countDown();
},String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println("班长锁门");
}
}
CyclicBarrier
//循环栅栏 收集7颗龙珠召唤神龙 加法
// CountDownLatch 是一次性的
// CyclicBarrier 是可循环利用的
// CountDownLatch 参与的线程的职责是不一样的,有的在倒计时,有的在等待倒计时结束。
// CyclicBarrier 参与的线程职责是一样的。
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,() -> {
System.out.println("召唤神龙");
});
for(int i = 1;i<=14;i++){
final int num = i;
new Thread(()->{
System.out.println("抢到了"+num);
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
Semaphore
//秒杀 acquire release
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(4);
for(int i = 1;i<= 6;i++){
new Thread(() -> {
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 {
semaphore.release(); //释放
}
},String.valueOf(i)).start();
}
}
}