CountDownLatch计数器
构造器传入int计数器参数,await()使线程等待,countDown()使计数器-1,当计数器为0时,唤醒await的线程继续执行
/**
* 演示CountDownLatch
*/
public class CountDownLatchDemo {
//6个同学陆续离开教室之后,班长锁门
public static void main(String[] args) throws InterruptedException {
//创建CountDownLatch对象,设置初始值
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " 号同学离开了教室");
//计数器 -1
countDownLatch.countDown();
}, String.valueOf(i)).start();
}
//等待
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + " 班长锁门走人");
}
}
CyclicBarrier循环栅栏
构造器传入int参数以及Runnable参数,调用await()等待线程数等于int参数时,执行Runnable参数的方法
/**
* 集齐7颗龙珠召唤神龙
*/
public class CyclicBarrierDemo {
//创建固定值
private static int NUMBER = 7;
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMBER, () -> {
System.out.println("集齐7颗龙珠召唤神龙");
});
//集齐七颗龙珠的过程
for (int i = 1; i <= 7; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " 星龙珠被收集到了");
//等待
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}
Semaphore信号灯
构造器传入int的资源参数,线程执行获取资源,最后释放资源,若当前无资源则等待其他线程释放资源
/**
* 6辆汽车停在3个停车位
*/
public class SemaphoreDemo {
public static void main(String[] args) {
//创建Semaphore,设置许可数量
Semaphore semaphore = new Semaphore(3);
//模拟6辆汽车
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() + " -------------离开了车位");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}