java 常用的辅助类:CountDownLatch,CyclicBarrier,Semaphore
java 常用的辅助类:
1.CountDownLatch减法计数器
2.CyclicBarrier加法计数器
3.Semaphore 同一时刻只允许固定(3)个线程执行,完成后另外固定(3)个线程再继续执行
1.CountDownLatch:减法计数器.等待所有的执行完成
CountDownLatch countDownLatch = new CountDownLatch(5);//减法计数器
for (int i = 0; i < 5; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"go out");
countDownLatch.countDown(); //减1
},"a").start();
}
countDownLatch.await(); //等待所有的执行完成
System.out.println("close door");//最后执行
2.CyclicBarrier加法计数器:等待直到7个线程执行完成
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("召唤神龙成功");
});
for (int i = 0; i < 7; i++) {
final int tem=i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"shouji" +tem+"ge longzhu");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
}).start();
}
3.Semaphore 同一时刻只允许3个线程执行,完成后另外3个线程再继续执行
// 线程数量:停车位有3个,开始停车3俩,等待1秒后释放,另外3个停车
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 10; i++) {
new Thread(()->{
try {
semaphore.acquire();//抢到线程 若已满则等待
System.out.println("抢到线程");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}finally {
semaphore.release(); //释放
}
},String.valueOf(i)).start();
}