我有一个简单的 Java 程序,它利用监视器让客户进入登机区。我认为我将 wait() 和 notify() 语句放置在导致程序死锁的错误位置,但是,我自己无法弄清楚。下面是我写的代码。
public class AdultCouple extends Thread
{
private boolean onRide = false;
private int ID;
AdultCouple(int ID)
{
this.ID = ID;
}
public synchronized void getIn()
{
while (!Main.isDoorOpen)
{
try
{
wait();
}
catch (InterruptedException ex)
{
}
System.out.println("Go through");
}
System.out.println("Couple " + ID + " get in boarding area.");
onRide = true;
Main.peopleInBoardingArea++;
notify();
}
public void run()
{
getIn();
}
}
public class Area extends Thread
{
Area()
{
}
public synchronized void openDoor()
{
while (Main.peopleInBoardingArea != 0)
{
try
{
wait();
}
catch (InterruptedException ex)
{
}
}
System.out.println("Area opens");
Main.isDoorOpen = true;
notifyAll();
}
public synchronized void closeDoor()
{
}
public void run()
{
openDoor();
}
}
public class ParentKid extends Thread
{
private boolean onRide = false;
private int ID;
ParentKid(int ID)
{
this.ID = ID;
}
public synchronized void getIn()
{
while (!Main.isDoorOpen)
{
try
{
wait();
}
catch (InterruptedException ex)
{
}
System.out.println("Go through");
}
System.out.println("Couple " + ID + " get in boarding area.");
onRide = true;
Main.peopleInBoardingArea++;
notify();
}
public void run()
{
getIn();
}
}
public class Main
{
public static boolean isDoorOpen = false;
public static int peopleInBoardingArea = 0;
public static void main(String args[])
{
Thread t3 = new Area();
Thread t1 = new ParentKid(1);
Thread t2 = new AdultCouple(2);
t1.start();
t2.start();
t3.start();
try
{
t1.join();
t2.join();
t3.join();
}
catch (InterruptedException ex)
{
}
}
}