如果我在主类中启动了五个将运行parralell
的线程final int TERMINAL_COUNT = 5;
Semaphore semaphore = new Semaphore(1);
Queue<Terminal> terminals = new LinkedList<>();
for (int i = 1; i<= TERMINAL_COUNT; i++){
terminals.offer(new Terminal(i, semaphore));
}
for(Terminal terminal : terminals) terminal.start();
}
带有它们的课程看起来像
public class Terminal extends Thread {
private Dispetcher dispetcher;
private Semaphore semaphore;
public Terminal(int terminalId, Semaphore semaphore){
dispetcher = new Dispetcher();
this.semaphore = semaphore;
}
@Override
public void run() {
try{
ListIterator<Plane> pIt = dispetcher.getPlanes().listIterator();
while (pIt.hasNext()){
Plane p = pIt.next();
if(!p.isArrived()) {
//some code
replacingPassangers(p);
}
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
private void replacingPassangers(Plane p) throws InterruptedException{
semaphore.acquire();
if(!p.isArrived()) {
//replacing passangers
p.setIsArrived(true);
}
semaphore.release();
}
}
所以我需要在乘客被1个线程替换后,其他人在if(!p.isArriving)条件的帮助下跳过方法逻辑。但是p.setIsArrived(true);不会影响其他线程中的这个变量,因此所有线程都会通过这个条件......我该如何修复它呢?