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輛車,先進入三輛車,如果一輛車出來,後來的車可以進去,但始終只有三輛車同時停到車位。