具有多个共享资源的线程

时间:2017-01-03 15:16:26

标签: java multithreading resources shared

我在Java大学项目上遇到了一些麻烦。

因此,该项目涉及机场(服务器)和发送物体(飞机)的客户,以模拟其在两个或多个着陆轨道上的到达。我没有手头的项目代码,所以我会尝试解释自己。

现在,我的问题不是项目的分布式部分。我真正的问题在于并发性。

因此,显然,每次只允许一架飞机降落在每条轨道上。

线程(飞机)调用机场方法

  (askLanding(Airplane ap)) 

btw,idk如果线程可以调用接收与参数相同的线程的方法

并且机场通过机场的每个轨道(环路)管理着陆并检查他们是否打开着陆(我可以选择在我想要的时候打开/关闭)着陆然后打电话给另一个方法,同步的:

  (tracks.get(i).toLand(ap))

如果另一架飞机正在使用该轨道,则该线程将等待()。

我的问题是,如果第一首曲目是开放的,每架飞机将在第一首曲目上等待,其他曲目将为空。如果我在askLanding()方法上检查轨道可用性,我将锁定共享资源及其轨道(机场)。即使飞机只使用其中一条轨道着陆,也没有其他飞机可以降落在任何其他轨道上。

我觉得我在某个地方犯了一个大错,但我无法看到它。我可以尽快在这里贴一些代码。

编辑:好的,这是一些代码:

飞机线程

公共类飞机扩展线程{

protected int tankCap;
protected int curFuel;
protected int flightNum;
protected int fuelCons;
protected Airport ap1;
protected boolean landed;
protected int time;
protected int priority;

public Aircraft(Airport ap1, int comb) {
    this.ap1 = ap1;
    flightNum = new Random().nextInt(300);
    this.curFuel = comb;
    this.landed = false;        
}

@Override
public void run() {
    ap1.reqLanding(this);
}

机场等级

公共类机场{

private LinkedList<Runway> runways;
private LinkedList<Aircraft> aircraftsToLand;



public Airport() {

    runways = new LinkedList<Runway>();
    aircraftsToLand = new LinkedList<Aircraft>();


}


public void reqLanding(Aircraft a){

    aircraftsToLand.add(a);

    for(int i = 0; i != runways.size(); i++){

        if(runways.get(i).getOpen()){
            runways.get(i).land(a);
        }
    }

}

跑道类 - 土地方法

public synchronized void land(Aircraft a){
    numLanding++;

    while(available == false){

        try {
            a.setFuel(a.getCurFuel() - a.getFuelCons());
            System.out.println(a.toString());
            wait();
        } catch (InterruptedException e) {
            System.out.println("Interrupted while on wait");
        }
    }
    available = false;
    runwayTxt.setText(a.toString());

    System.out.println(getnPista().getText() + " A aterrar:" + a.toString());
    try {
        Thread.sleep(6000);
    } catch (InterruptedException e) {
    }
    System.out.println(getnPista().getText() + " Aterrou:" + a.toString());

    runwayTxt.setText("");
    numLanding--;
    a.setLanding(true);
    available = true;
    notifyAll();
}

由于

0 个答案:

没有答案
相关问题