这里写自定义目录标题
CyclicBarrier
多线程执行的时候确保所有线程到达同一位置后再执行。
ThreadPoolExecutor
线程池,避免频繁新建现场的损耗。
代码示例
package com.fancv.concurrent.ThreadWait;
import java.util.concurrent.*;
/**
* 要求是一组任务
* 3 个线程 协作完成一个任务,3个线程都执行完成了 主线程打印任务结果
* 重试3次
*/
public class CyclicBarrierDemo_2 {
ThreadPoolExecutor threadPoolExecutor =new ThreadPoolExecutor(2, 9,
10L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(3));
CyclicBarrier cyclicBarrier = new CyclicBarrier(3,()->{
System.out.println(Thread.currentThread().getName()+"完成了一组之后 回调执行");
});
public static void main(String[] args) throws InterruptedException {
CyclicBarrierDemo_2 cyclicBarrierDemo_2=new CyclicBarrierDemo_2();
cyclicBarrierDemo_2.threeTime();
//执行shutdown
if (!cyclicBarrierDemo_2.threadPoolExecutor.isShutdown()) {
cyclicBarrierDemo_2.threadPoolExecutor.shutdown();
System.out.println("start shutdown ...");
//等待执行结束
cyclicBarrierDemo_2.threadPoolExecutor.awaitTermination(16, TimeUnit.MINUTES);
}
}
void threeTime(){
for (int i=0;i<3;i++){
threadPoolExecutor.submit(()->{
System.out.println("A");
try {
Thread.sleep(100);
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("A 执行完毕");
});
threadPoolExecutor.submit(()->{
System.out.println("B");
try {
Thread.sleep(1000);
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("B 执行完毕");
});
threadPoolExecutor.submit(()->{
System.out.println("C");
try {
Thread.sleep(1000);
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("C 执行完毕");
});
}
}
}
如果线程池参数配置为无界队列那么整个逻辑无法执行,CyclicBarrier 等待三个线程执行完毕,线程池只有两个工作线程,导致资源等待。