CountDownLatch 倒数的门栓
- CountDownLatch latch = new CountDownLatch(threads.length); 创建一个门栓,在门栓上面记个数
- 每一个线程结束就countDown
- 开启线程
- latch.await(); 每一个线程结束后线程数减一,当 latch.await()为0的时候门栓就打开
package com.mashibing.juc.c_020;
import java.util.concurrent.CountDownLatch;
public class T06_TestCountDownLatch {
public static void main(String[] args) {
usingJoin();
usingCountDownLatch();
}
private static void usingCountDownLatch() {
Thread[] threads = new Thread[100];
//创建一个门栓在门栓上面记个数
CountDownLatch latch = new CountDownLatch(threads.length);
for(int i=0; i<threads.length; i++) { //每一个线程结束就countDown
threads[i] = new Thread(()->{
int result = 0;
for(int j=0; j<10000; j++) result += j;
latch.countDown();
});
}
//线程开启
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
try { //门栓,拴住不动
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end latch");
}
private static void usingJoin() {
Thread[] threads = new Thread[100];
for(int i=0; i<threads.length; i++) {
threads[i] = new Thread(()->{
int result = 0;
for(int j=0; j<10000; j++) result += j;
});
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("end join");
}
}