线程协作
1.什么是控制并发流程
2.CountDownLatch
CountDownLatch的作用
CountDownLatch的主要方法
/**
* @Classname CountDownLatchDemo01
* @Description 工厂中,质检,5个工人,所有人都认为通过,才通过。
* @Date 2021/2/26 14:55
* @Created by YoungLiu
*/
public class CountDownLatchDemo01 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
ExecutorService service = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
final int no =i+1;
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
Thread.sleep((long) (Math.random() * 10000));
System.out.println("No." + no + " 完成了检查");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
}
};
service.submit(runnable);
}
System.out.println("等待5个人的检查....");
countDownLatch.await();
System.out.println("检查完毕");
}
}
3.Semaphore
主要方法介绍
注意点
4. Condition接口(条件对象)
4.1 作用
4.2 代码演示
/**
* @Classname ConditionDemo01
* @Description 演示condition基本用法
* @Date 2021/2/26 15:51
* @Created by YoungLiu
*/
public class ConditionDemo01 {
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
void method1(){
lock.lock();
try{
System.out.println("条件不满足,开始await");
condition.await();
System.out.println("条件满足了,开始执行后续任务");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
void method2(){
lock.lock();
try{
System.out.println("准备工作完成,开始唤醒其他的线程");
condition.signal();
}finally {
lock.unlock();
}
}
public static void main(String[] args) {
ConditionDemo01 conditionDemo01 = new ConditionDemo01();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
conditionDemo01.method2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
conditionDemo01.method1();
}
}
4.3 注意点
5.CyclicBarrier
/**
* @Classname CyclibarrierDemo
* @Description TODO
* @Date 2021/2/26 16:22
* @Created by YoungLiu
*/
public class CyclibarrierDemo01 {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {
@Override
public void run() {
System.out.println("所有人都到场了,大家统一出发");
}
});
for (int i = 0; i < 5; i++) {
new Thread(new Task(i,cyclicBarrier)).start();
}
}
static class Task implements Runnable{
private int id;
private CyclicBarrier cyclicBarrier;
public Task(int id,CyclicBarrier cyclicBarrier){
this.id = id;
this.cyclicBarrier=cyclicBarrier;
}
@Override
public void run() {
System.out.println("线程 "+ id + "现在前往集合地铁");
try {
Thread.sleep((long)(Math.random()*10000));
System.out.println("线程 "+ id + "到了集合地点,开始等待其他人到达");
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}