1、CountDownLatch 每次有线程调用,countDown()数量-1,假设计数器变为0,countdownlatch.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()+"Go Out");
countDownLatch.countDown();
},String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println("Close Door");
}
}
2、 CyclicBarrier减法计数器
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier=new CyclicBarrier(7,()->{
System.out.println("成功");
});
for (int i = 1; i <=7; i++) {
final int temp=i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"收集");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
3、Semaphore:信号量
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(2);
System.out.println(Thread.currentThread().getName() + "逃离");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
原理: semaphore.acquire() 获得,当已经满了,等待被释放为止 semaphore.release() 释放,会将当前的释放量+1,然后唤醒等待的线程! 作用:多个共享资源互斥的使用!并发限流,控制最大的线程数!
本篇文章是在哔哩哔哩听了狂神老师的JUC课程记录的笔记!方便自己查看!
|