CountDownLatch - latch.await() 可以理解為門栓栋盹,線程每完成一個執(zhí)行l(wèi)atch.countDown(),即為減1敷矫,直至減到0例获,latch.await() 才會執(zhí)行,new CountDownLatch(threads.length)設(shè)置線程的數(shù)量
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++) {
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");
}
}
CyclicBarrier - 循環(huán)柵欄曹仗,即為滿了執(zhí)行榨汤。
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class T07_TestCyclicBarrier {
public static void main(String[] args) {
// 參數(shù)1:設(shè)置待滿足的數(shù)量條件 參數(shù)2:條件滿足后 執(zhí)行的邏輯
CyclicBarrier barrier = new CyclicBarrier(20, () -> System.out.println("滿人,發(fā)車"));
/*CyclicBarrier barrier = new CyclicBarrier(20, new Runnable() {
@Override
public void run() {
System.out.println("滿人怎茫,發(fā)車");
}
});*/
for(int i=0; i<100; i++) {
new Thread(()->{
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
-
場景 - 不同的線程處理不同的操作收壕,等待三個線程都完成的各自的操作之后,才能進行下一步操作轨蛤。