gpt4 book ai didi

java - 循环屏障异常处理

转载 作者:行者123 更新时间:2023-11-30 08:10:24 25 4
gpt4 key购买 nike

我遇到循环屏障问题,请查看下面的代码 -

MeetingPoint1.java

public class MeetingPoint1 implements Runnable{

@Override
public void run() {
System.out.println(" MeetingPoint1 one cleared... ");
}

}

MeetingPoint2.java

public class MeetingPoint2 implements Runnable{

@Override
public void run() {
System.out.println(" MeetingPoint Two cleared... ");
}

}

VehicalRunnable.java

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
* @author chouhan_r
*
*/
public class VehicleRunnable implements Runnable {

private CyclicBarrier barrier1;
private CyclicBarrier barrier2;

public VehicleRunnable(CyclicBarrier barrier1, CyclicBarrier barrier2) {
this.barrier1 = barrier1;
this.barrier2 = barrier2;
}

/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() +" Waiting at Meeting Point 1");
if(Thread.currentThread().getName().equalsIgnoreCase("Car")){
throw new RuntimeException("something weird happened");
}
barrier1.await();
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() +" Waiting at Meeting Point 2");
barrier2.await();

} catch(BrokenBarrierException | RuntimeException | InterruptedException e){
e.printStackTrace();
}

}

}

CyclicBarrierMain.java

import java.util.concurrent.CyclicBarrier;

/**
* @author chouhan_r
*
*/
public class CyclicBarrierMain {

/**
* @param args
*/
public static void main(String[] args) {
MeetingPoint1 meetingPoint1 = new MeetingPoint1();
MeetingPoint2 meetingPoint2 = new MeetingPoint2();

CyclicBarrier barrier1 = new CyclicBarrier(3, meetingPoint1);
CyclicBarrier barrier2 = new CyclicBarrier(3, meetingPoint2);

VehicleRunnable car = new VehicleRunnable(barrier1, barrier2);
VehicleRunnable bike = new VehicleRunnable(barrier1, barrier2);
VehicleRunnable bus= new VehicleRunnable(barrier1, barrier2);
new Thread(car,"Car").start();
new Thread(bike,"Bike").start();
new Thread(bus,"Bus").start();
}

}

当线程抛出一些异常时,所有其他线程都在屏障 1 处等待,有什么方法可以运行等待线程直到屏障 2 吗?将barrier.await()方法放在finally block 中是不是一个更好的主意?

最佳答案

您正在使用计数器 3 创建循环屏障。其中两个线程能够调用 Barrier1.await();因此等待计数器为零,以便它们可以继续进行,但第三个线程无法调用barrier1.await(),因为您在调用barrier.await()之前已显式抛出异常。因此计数器不会为零,并且所有其他线程将卡在barrier1.await()处。

如果你想让所有其他线程继续进行,你必须在抛出异常之前再次调用barrier.await(),就像在这个 block 中一样。

 if(Thread.currentThread().getName().equalsIgnoreCase("Car")){
barrier1.await(); // call here
throw new RuntimeException("something weird happened");
}

关于java - 循环屏障异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30476807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com