CountDownlatch allows a thread or plurality of threads waiting for other threads to finish.
If there is such a demand:
We need to parse data from multiple Excel sheet inside of a case, you can consider using multiple threads, each parse the data in a sheet, sheet until all are resolved over, the program requires prompt completion of the analysis.
Use CountDownLatch achieve the following:
import java.util.concurrent.CountDownLatch;
/**
* @Description
* @Author DJZ-WWS
* @Date 2019/5/27 14:57
*/
public class TestCountDownLatch {
static CountDownLatch countDownLatch = new CountDownLatch(2);
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第一个sheet解析完毕");
//没调用一次这个方法,构造器里的初始值就会减一
countDownLatch.countDown();
}).start();
new Thread(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第二个sheet解析完毕");
//没调用一次这个方法,构造器里的初始值就会减一
countDownLatch.countDown();
}).start();
System.out.println("主线开始等待");
countDownLatch.await();
System.out.println("所有的sheet解析完毕,继续执行后面的操作");
}
}
Execution results are as follows:
CountDownLatch constructor receives as a parameter of type int counter, if you want to wait for the completion of N points, where it is passed N.
When we call countDown method of CountDownLatch, N will be minus one, await his method blocks the current thread until N becomes zero.
Since countDown method can be used anywhere, where said N points, may be an N threads, one thread may be inside the N operations. When used in a multi-threaded, this CountdownLatch just need to pass a reference to the thread can be.
If the resolution of a sheet of threading slow, we can not let the main thread waits can use all await another method with the specified time -await (long time, TimeUnit unit)
Note that the current thread does not block the counter must be greater than or equal to 0, but when the counter is equal to 0 0. invoked await. countDownLatch impossible to re-initialize or modify the value of the internal counter CountDownLatch.
Here is another similar example:
package juc.currnet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Description 该程序用来模拟发送命令与执行命令,主线程代表指挥官,新建3个线程代表战士,战士一直等待着指挥官下达命令,
* *若指挥官没有下达命令,则战士们都必须等待。一旦命令下达,战士们都去执行自己的任务,指挥官处于等待状态,战士们任务执行完毕则报告给
* @Author DJZ-WWS
* @Date 2019/4/13 15:25
*/
public class CountDownLatchTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
//模拟命令
CountDownLatch cdOrder = new CountDownLatch(1);
//模拟战士,多个线程
CountDownLatch answer = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
//战士待命状态
System.out.println("线程" + Thread.currentThread().getName() + "正在准备待命");
//个人理解,到目前为止还没有向线程池提交任务,等待的线程为主xianc
cdOrder.await();
System.out.println("线程" + Thread.currentThread().getName() + "已接受命令");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程" + Thread.currentThread().getName() + "回应命令处理结果");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
answer.countDown();
}
}
};
service.execute(runnable);//为线程池添加任务
}
try {
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程" + Thread.currentThread().getName() + "即将发布命令");
cdOrder.countDown(); //发送命令,cdOrder减1,处于等待的战士们停止等待转去执行任务。
System.out.println("线程" + Thread.currentThread().getName() + "已发送命令,正在等待结果");
answer.await(); //命令发送后指挥官处于等待状态,一旦cdAnswer为0时停止等待继续往下执行
System.out.println("线程" + Thread.currentThread().getName() + "已收到所有响应结果");
} catch (Exception e) {
e.printStackTrace();
} finally {
}
service.shutdown(); //任务结束,停止线程池的所有线程
}
}
The results are as follows:
Still I remember just now to this company when I was head of the interview I asked the class, I remember cited an example:
Analog family to dinner, people went uncertainty, must wait until the person in attendance before they can eat, this time we can use this tool class. At that time I was so answer was, did not continue to ask down.
Reference: "java concurrent programming art"