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();
}
}
}