减少计数 CountDownLatch
CountDownLatch对象的 await方法是阻塞式的,计数为0才通过。 countDown() 不是阻塞的,会使计数减一
例子: 6个同学离开教室后,班长才可以锁门
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(()->{
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName() + "号同学离开了教室");
}, String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + "班长锁门走了");
}
}
循环栅栏CyclicBarrier
例子:及其七颗龙珠即可召唤神龙(继续执行)
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++) {
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName() + "星龙珠被收集到了");
cyclicBarrier.await();
System.out.println("哈哈哈");
} catch (Exception e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}
信号灯Semaphore
acquire() 方法,从此信号量中获取一个许可,在提供一个许可前线程将一直阻塞 release() 释放一个许可,将其返回给信号量
例子:六辆汽车,停在三个车位
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(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName() + "------离开了停车位");
} catch (Exception e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}
|