目录
一、CountDownLatch是什么?
CountDownLatch中count down是倒数的意思,latch则是门闩的含义。整体含义可以理解为倒数的门栓,似乎有一点“三二一,芝麻开门”的感觉。CountDownLatch的作用也是如此,在构造CountDownLatch的时候需要传入一个整数n,在这个整数“倒数”到0之前,主线程需要等待在门口,而这个“倒数”过程则是由各个执行线程驱动的,每个线程执行完一个任务“倒数”一次。总结来说,CountDownLatch的作用就是等待其他的线程都执行完任务,必要时可以对各个任务的执行结果进行汇总,然后主线程才继续往下执行。
二、使用CountDownLatch
创建:
new CountDownLatch(倒数的数字)
主要方法:
void countDown() 倒数一次,数字减一
void await() 阻塞当前线程,当倒数为0就唤醒
代码如下(示例):
public class CountDownLatchDemo {
public static void main(String[] args) {
//创建倒数对象
CountDownLatch latch = new CountDownLatch(3);
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"在等待其它线程!!");
try {
//等待其它线程结束
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" finished!!");
}).start();
for (int j = 0; j < 3; j++) {
new Thread(()->{
for(int i = 0;i < 5;i++){
System.out.println(Thread.currentThread().getName()+"-->"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//倒数一次
latch.countDown();
System.out.println(Thread.currentThread().getName()+" finished,count=" + latch.getCount());
}).start();
}
}
Semaphore 类
信号量,控制启动线程的数量
创建:
new Semaphore(最大数量)
常见使用方法:
aquired() 请求一个信号量
release() 释放一个信号量
public class SemaphoreDemo {
public static void main(String[] args) {
//创建信号量
Semaphore semaphore = new Semaphore(5);
for(int i = 0;i < 100;i++){
//启动线程
new Thread(() -> {
try {
//请求信号量
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"启动了");
Thread.sleep(1000);
//释放信号量
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
}