package test;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Program: csdn @ClassName: CyclicBarrierTest
* @Author: shiyu.
* @Date: 2022-06-24 17:09
* @Description: 循环屏障工具
* @Version: V1.0
*/
@Slf4j
public class CyclicBarrierTest {
public static final ExecutorService executorService = Executors.newFixedThreadPool(50);
@Getter
@Setter
public static class SegmentedTask {
private Runnable start;
private Runnable middle;
private Runnable end;
public SegmentedTask(Runnable start, Runnable middle, Runnable end) {
this.start = start;
this.middle = middle;
this.end = end;
}
}
/**
* 提交任务
*
* @param tasks 参数
*/
public static void submit(List<SegmentedTask> tasks) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(tasks.size() + 1);
try {
tasks.forEach(task -> executorService.submit(() -> {
try {
task.getStart().run();
cyclicBarrier.await();
task.getMiddle().run();
cyclicBarrier.await();
task.getEnd().run();
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}));
cyclicBarrier.await();
log.info("初始任务已经全部完成");
cyclicBarrier.await();
log.info("中间任务已经全部完成");
cyclicBarrier.await();
log.info("最终任务已经全部完成");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
public static void destroy() {
log.info("摧毁线程池");
executorService.shutdown();
}
public static void main(String[] args) throws InterruptedException {
Random random = new Random();
List<SegmentedTask> tasks = new ArrayList<>();
for (int i = 1; i < 11; i++) {
int finalI = i;
tasks.add(new SegmentedTask(() -> {
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info(Thread.currentThread() + ":" + MessageFormat.format("第{0}军团已经开始推进!", finalI));
}, () -> {
try {
Thread.sleep(random.nextInt(2000));
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info(Thread.currentThread() + ":" + MessageFormat.format("第{0}军团已经正在进攻!", finalI));
}, () -> {
try {
Thread.sleep(random.nextInt(3000));
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info(Thread.currentThread() + ":" + MessageFormat.format("第{0}军团已经攻陷阵地!", finalI));
}));
}
CyclicBarrierTest.submit(tasks);
Thread.sleep(10000);
CyclicBarrierTest.destroy();
}
}
CyclicBarrierTest简单实现测试类
于 2023-05-29 14:29:16 首次发布