一、CountDownLatch
CountDownLatch(倒计时计数器、闭锁),让一些线程阻塞直到另一些线程完成一些操作才被唤醒
CountDownLatch主要有两个方法:当一个或多个线程调用await()方法时,调用线程会被阻塞;其他线程调用countDown()方法会将计数器减一,调用countDown()方法不会被阻塞
当计数器的值为0时,调用await()方法被阻塞的线程会被唤醒
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
for(int i = 0; i < 5; i++){
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(1);//睡眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "t 线程");
countDownLatch.countDown(); //计数器减一
}, String.valueOf(i)).start();
}
countDownLatch.await();//计数器为0时,唤醒线程
System.out.println(Thread.currentThread().getName() + "t 线程");
}
}
结果:
二、CyclicBarrier
CyclicBarrier(可循环屏障,栅栏),让一组线程到达一个屏障(同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,线程才会继续执行
public class CyclicBarrierTest {
public static void main(String[] args) {
// CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
CyclicBarrier cyclicBarrier = new CyclicBarrier(3, ()->{
System.out.println(Thread.currentThread().getName() + "t work");
});
for(int i = 0; i < 6; i++){
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "t begin");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "t end");
}, String.valueOf(i)).start();
}
}
}
结果:
三、Semaphore
Semaphore(信号量),主要用于两个目的,一个是用于多个共享资源的互斥作用,另一个用于并发线程数的控制
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);//模拟3个停车位
for(int i = 0; i < 6; i++){//模拟6部汽车
new Thread(()->{
try {
semaphore.acquire();
int time = (int)(1+Math.random()*(10-1+1));
System.out.println(Thread.currentThread().getName() + "t抢到车位, 使用"+time+"秒");
TimeUnit.SECONDS.sleep(time);
System.out.println(Thread.currentThread().getName() + "t离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}
结果: