CountDownLatch(减法计数器)
计数器
具体使用,只有计数器归零了主线程才能继续向下执行(即计数器归零后,await()才会被唤醒)
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6 ; i++) {
new Thread(() -> {
System.out.println("第" + Thread.currentThread().getName() + "人出门了") ;
countDownLatch.countDown(); //数量-1
}, String.valueOf(i + 1)).start();
}
countDownLatch.await(); //等待计数器归零,才会继续执行下去
System.out.println("门关上了");
}
}
CyclicBarrier(加法计数器)
加法计数器代码
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("召唤神龙成功");
});
for (int i = 0; i < 7; i++) {
new Thread(() -> {
System.out.println("收集了" + Thread.currentThread().getName() + "颗龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}, String.valueOf(i +1)).start();
}
}
}
只有当七个线程中的await都执行到了才会执行cyclicBarrier的第二个参数方法,该类两个构造方法
Semaphore
Semaphore:信号量,限流使用
具体实现,抢车位,三个车位6辆车
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 6; i++) {
new Thread(() -> {
try {
semaphore.acquire(); //得到
System.out.println(Thread.currentThread().getName() + "抢到了车位");
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName() + "离开了车位");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release(); //释放
}
}, String.valueOf(i + 1)).start();
}
}
}
原理:
semaphore.acire() 获得,假设如果已经满了则等待,等待到释放为止
semaphore.release()释放,会将当前的信号量释放+1,然后唤醒等待的线程!
作用:多个共享资源互斥的使用!并发限流,控制最大的线程数!