CyclicBarrier
应用场景是比如在做压力测试时,使用多少个用户并发,做集合点测试。
比如设置 100个用户并发,100个用户同时进行压测,只有100个用户压测完毕时,才能再发起下一波的压力测试。
package com.study.juc; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class CyclicBarrierDemo { public static void main(String[] args) throws BrokenBarrierException, InterruptedException, TimeoutException { CyclicBarrier cyclicBarrier=new CyclicBarrier(2,()->{ System.err.println( "集合完毕出发!"); }); for(int i=1;i<=3;i++){ int tmp = i; new Thread(()->{ System.err.println(Thread.currentThread().getName() +"线程before:"+ tmp); try { cyclicBarrier.await(2, TimeUnit.SECONDS); System.err.println(Thread.currentThread().getName() +"线程after:"+ tmp); } catch (Exception e) { e.printStackTrace(); } },"CyclicBarrier").start(); } } }
CountDownLatch
减法计数器。
package com.study.juc; import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch latch=new CountDownLatch(13); for(int i=1;i<=12;i++){ new Thread(()->{ System.err.println(Thread.currentThread().getName() +"before:" +latch.getCount()); latch.countDown(); System.err.println(Thread.currentThread().getName() +"after :" +latch.getCount()); },String.valueOf(i)).start(); } latch.await(); } }
使用信号量
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore=new Semaphore(3);
Random random=new Random();
for(int i=1;i<=6;i++){
new Thread(()->{
try {
semaphore.acquire();
int second=random.nextInt(10);
System.err.println(Thread.currentThread().getName() +"时长"+second +"开始");
TimeUnit.SECONDS.sleep(second);
System.err.println(Thread.currentThread().getName()+"完成");
}
catch (InterruptedException ex){
ex.printStackTrace();
}
finally {
semaphore.release();
}
},"线程" +i).start();
}
}
}
信号量的作用是:比如有三个车位,有6辆车,先进入三辆车,如果一辆车出来,后来的车可以进去,但始终只有三辆车同时停到车位。