If that (summary points)
- CountDownLatch countdown latch device,
- Allow 1-n-1 threads waiting for other multithreading job done.
- (Sheet of resolving multiple Excel, and ultimately wait parsed completely; to achieve the main thread waits for all threads to complete sheet resolve operation, the easiest is to join)
- CountDownLatch latch = new CountDownLatch (2); // use count down latch is forced into the main thread wait; set of N nodes, threads or n-steps
- latch.countDown();
- latch.await (1000, TimeUnit.MILLISECONDS); // blocks the current thread until the counter becomes 0
- Original link:
Learn from the article list
- ALiBaBaJavaCodingGuideLines something to say:
- Use the thread pool better!
Simple Test 1. Test 1
public class Test03_countdownlatch {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("hello ");
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
System.out.println("all thread finish");
}
}
2. Results 1: the thread has not finished in time, the main thread is over, so the first print finish
all thread finish
hello
hello
3. Test 2 forcing the main thread waits for the current sub-thread is finished by the join method of sub-thread
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("hello ");
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
try {
// 迫使主线程通过join方法等待当前的子线程执行完毕
thread1.join();
// 主线程第二次等待
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("all thread finish");
}
Test Results
hello
hello
all thread finish
Test 3 is used to count down latch
public static void main(String[] args) {
Runnable runnable = () -> System.out.println("hello ");
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
// 使用倒计数门闩器 ,迫使主线程进入等待 ;设置N个结点 ,n个线程或者步骤都可以
CountDownLatch latch = new CountDownLatch(2);
thread1.start();
latch.countDown();
thread2.start();
latch.countDown();
try {
// 阻塞当前线程,直到计数器变为0; await(long time);也可以带时间!
latch.await(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("all thread finish");
}
Test Results
hello
hello
all thread finish