Java Multithreading Semaphore

可紊 提交于 2019-12-24 00:03:25

问题


If I launch for example five threads in main class that will be running 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();
 }

And class that carries them looks like

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();
}
}

So i need that after passengers is replaced by 1 thread the others skip methods logic with help of if(!p.isArriving) condition. But p.setIsArrived(true); doesn't affects this variable in other threads and as result all threads passing this condition... How can I fix it?

来源:https://stackoverflow.com/questions/36453343/java-multithreading-semaphore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!