1、倒计数闩锁 CountDownLatch
/**
* 倒计数闩锁
* 等班里5个学生都走出教室后,老师才能走出去
*/
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
for (int i = 1; i <= 5; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName()+" 走出了教室 ");
countDownLatch.countDown(); // 到这里只是给计数器减一,并不会阻塞(和CyclicBarrier区别)
System.out.println("不阻塞");
},String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println("老师走");
}
}
2、循环栅栏
/**
* 循环栅栏
* 收集完7颗龙珠,才能召唤神龙
*/
public class CyclicBarrierDemo {
private static final int NUMBER = 7;
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMBER, () -> {
System.out.println("召唤神龙!");
});
for (int i = 1; i <= 7; i++) {
int finalI = i;
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " 拿到龙珠");
try {
cyclicBarrier.await(); // 到这里会阻塞,直到所有线程都达到这个点,cyclicBarrier到达阈值才往下执行(和CountDownLatch区别)
System.out.println(finalI);
} catch (Exception e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}
3、信号量
/**
* 有6辆汽车,停2个车位,每辆车随机停数秒
* (信号量的本质是保证多个线程中,只能有指定数量的线程同时工作)
*/
public class SemaphoreDemo {
public static void main(String[] args) {
// 设置许可变量
Semaphore semaphore = new Semaphore(2);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
try {
// 抢占
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " --> 抢到停车位");
// 设置随机停车时间
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName() + " ----------> 离开车位");
// 释放
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}