一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第18天,点击查看活动详情。
CyclicBarrier下 使用方法isBroken()检查屏障损坏性
实现类代码如下:
public class CyclicBarrierBrokenService {
private CyclicBarrier cyclicBarrier;
public CyclicBarrierBrokenService(CyclicBarrier cyclicBarrier){
super();
this.cyclicBarrier=cyclicBarrier;
}
private void startRun(int count){
try {
System.out.println(Thread.currentThread().getName()+" 到了 在等待其他人都到了开始起跑");
if(Thread.currentThread().getName().equals("Thread-2")){
System.out.println("Thread-2 进来了");
Thread.sleep(5000);
Integer.parseInt("A");
}
cyclicBarrier.await();
System.out.println(" 都到了,开始跑!");
System.out.println(Thread.currentThread().getName()+" 到达终点,并结束第 "+count+"赛段");
} catch (InterruptedException e) {
System.out.println("进入了InterruptionedException e"+cyclicBarrier.isBroken());
e.printStackTrace();
} catch (BrokenBarrierException e) {
System.out.println("进入了BrokenBarrierException e"+cyclicBarrier.isBroken());
e.printStackTrace();
}
}
public void call(){
for (int i = 0; i < 1; i++) {
startRun(i+1);
}
}
}
线程执行代码如下:
public class BrokenThread implements Runnable{
private CyclicBarrierBrokenService cyclicBarrierBrokenService;
public BrokenThread(CyclicBarrierBrokenService cyclicBarrierBrokenService){
super();
this.cyclicBarrierBrokenService=cyclicBarrierBrokenService;
}
@Override
public void run() {
cyclicBarrierBrokenService.call();
}
}
运行类代码如下:
public class CyclicBarrierBrokenRun {
public static void main(String[] args) {
int parties = 4;
CyclicBarrier cyclicBarrier = new CyclicBarrier(parties, new Runnable() {
@Override
public void run() {
System.out.println(" 都到了!");
}
});
CyclicBarrierBrokenService cyclicBarrierBrokenService = new CyclicBarrierBrokenService(cyclicBarrier);
BrokenThread[] brokenThreads = new BrokenThread[4];
for (int i = 0; i <brokenThreads.length ; i++) {
brokenThreads[i] = new BrokenThread(cyclicBarrierBrokenService);
new Thread(brokenThreads[i]).start();
}
}
}
运行结果如下:
Thread-1 到了 在等待其他人都到了开始起跑
Thread-0 到了 在等待其他人都到了开始起跑
Thread-3 到了 在等待其他人都到了开始起跑
Thread-2 到了 在等待其他人都到了开始起跑
Thread-2 进来了
Exception in thread "Thread-2" java.lang.NumberFormatException: For input string: "A"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at com.ozx.concurrentprogram.cyclicBarrier.service.CyclicBarrierBrokenService.startRun(CyclicBarrierBrokenService.java:25)
at com.ozx.concurrentprogram.cyclicBarrier.service.CyclicBarrierBrokenService.call(CyclicBarrierBrokenService.java:41)
at com.ozx.concurrentprogram.cyclicBarrier.entity.BrokenThread.run(BrokenThread.java:22)
at java.lang.Thread.run(Thread.java:748)
从运行结果来看,有一个线程出现异常报错,则其他线程继续等待,并不影响程序运行的主流程。可以使用方法isBroken()来查询此屏障是否处于损坏状态。