常用辅助类
CountDownLatch:用来计数减一的辅助工具类
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();//-1
},String.valueOf(i)).start();
}
countDownLatch.await();//等待计数器归零,然后再向下执行
System.out.println("close Door");
}
}
每次有线程调用countDown()数量减一,假设计数器变为0,await()方法就会被唤醒,继续执行。
countDownLatch.countDown();//-1
countDownLatch.await();//等待计数器归零,然后再向下执行
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()+"收集"+temp+"颗龙珠");
try {
cyclicBarrier.await();//等待
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
cyclicBarrier.await();//等待计数+1
Semaphore:信号量
6车-3个停车位
//限流时使用,使之有秩序
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);//默认线程数量:停车位
for (int i = 1; i <= 6; i++) {
new Thread(()->{
//acquire() 获得
//release() 释放
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();
}
}
}
原理:
acquire()获取,假设如果已经满了,等待被释放为止
release()释放,会将当前的信号量释放+1,然后唤醒等待的线程
作用:
多个共享资源互斥使用,并发限流,控制最大的线程数