1.CountDownLatch 的使用
應用場景:
等待已知數量的線程執行完後 ,在喚醒當前的主線程的應用場景,比如:查詢所有航空公司的機票,多個線程單獨執行查詢單個航空公司的機票,所有的單個線程結束後,環境主線程,將結果輸出。
相當於計數器進行減的操作
實例代碼:
package com.lhj;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLatchDemo {
//針對航班查詢進行舉例
private static List<String> company = Arrays.asList("東方航空", "南方航空", "海南航空");
private static List<String> fightList = new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
String origin = "PEK";
String dest = "pvg";
Thread[] threads = new Thread[company.size()];
CountDownLatch countDownLatch = new CountDownLatch(company.size());
for (int i = 0; i < threads.length; i++) {
final String companyName = company.get(i);
threads[i] = new Thread(() -> {
System.out.println(companyName + "查詢飛機票從"+origin+"到" + dest);
//隨機產生票數
int paperNum = new Random().nextInt(10);
try {
TimeUnit.SECONDS.sleep(paperNum);
} catch (InterruptedException e) {
e.printStackTrace();
}
fightList.add(companyName + "--" + paperNum);
System.out.printf("%s公司查詢成功!\n", companyName);
countDownLatch.countDown();
});
threads[i].start();
}
countDownLatch.await();
System.out.println("==============查詢結果如下:================");
fightList.forEach(System.out::println);
}
}
運行結果
2.CyclicBarrier的使用
應用場景:
等待所有線程開啓完成後,喚醒主線程,例如
等該所有參賽的運動員參賽全部到位後,開始比賽
相當於計數器進行加的操作
示例代碼:
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
public class CyclicBarrierDemo {
public static void main(String[] args) {
Thread[] running = new Thread[8];
CyclicBarrier cyclicBarrier = new CyclicBarrier(running.length);
for (int i = 0; i < running.length; i++) {
running[i] = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(new Random().nextInt(10));
System.out.println(Thread.currentThread().getName() + "準備好了!");
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("選手" + Thread.currentThread().getName() + "起跑");
}, "player" + i);
running[i].start();
}
}
}