我想对机场监视器(试图到达的飞机,试图离开的飞机等)进行编码,但我遇到了一些问题。只有一个线程似乎在工作,其他线程被卡在某个地方。有人可以看看这段代码并提供帮助吗?
public class Lotniskowiec {
public int K=5;
public int N = 10;
final Lock lock = new ReentrantLock();
final Condition toStart = lock.newCondition();
final Condition toLand= lock.newCondition();
boolean wantsToStart;
boolean wantsToLand;
int atAirport= 0;
boolean free= true;
private void free_landing_area(){
lock.lock();
if(atAirport< K){
if(wantsToLand){
toLand.signal();
}else toStart.signal();
}
else{
if(wantsToStart){
toStart.signal();
} else if (atAirport< N){
toLand.signal();
}
}
lock.unlock();
}
public void wants_to_start(){
lock.lock();
if(!free){
lock.unlock();
try {
toStart.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.lock();
free=false;
lock.unlock();
}
public void started(){
lock.lock();
atAirport-=1;
free=true;
free_landing_area();
lock.unlock();
}
public void wants_to_land(){
lock.lock();
if(!free|| atAirport==N){
lock.unlock();
try {
toLand.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.lock();
free=false;
lock.unlock();
}
public void landed(){
lock.lock();
atAirport+=1;
free=true;
free_landing_area();
lock.unlock();
}
}
很抱歉变量的名称;)
线程:
public class Samolot implements Runnable{
Random random = new Random();
Lotniskowiec lotniskowiec = new Lotniskowiec();
int id;
public Samolot(int id, Lotniskowiec lotniskowiec){
this.id=id;
this.lotniskowiec=lotniskowiec;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(random.nextInt(1000));
Lotniskowiec.wants_to_land();
System.out.println(id + " chce ladowac");
Thread.sleep(random.nextInt(1000));
Lotniskowiec.landed();
System.out.println(id + " wyladowal");
Thread.sleep(random.nextInt(1000));
Lotniskowiec.wants_to_start();
System.out.println(id + " chce startowac");
Thread.sleep(random.nextInt(1000));
Lotniskowiec.started();
System.out.println(id + " wystartowal");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
开始线程:
Samolot r = new Samolot(1,lotniskowiec);
Thread t = new Thread(r);
t.start();