我有这个练习,一种医院模拟,我必须控制每个奇异房间的访问。医生可以一次进入房间,只有在没有访客进入的情况下才可以进入。如果没有医生,访客只能访问房间,最多可以有4位访客。这是我的代码:
public class Room {
public Room(){
}
public synchronized void friendVisit() throws InterruptedException{
if(visitors>4 || doctors>0)
wait();
visitors++;
}
public synchronized void exitFriend(){
visitors--;
notify();
}
public synchronized void doctorVisit() throws InterruptedException{
if(doctors>0 || visitors>0)
wait();
doctors++;
}
public synchronized void exitDoctor(){
--doctors;
notify();
}
public int getVisitors(){
return visitors;
}
public int getDoctors(){
return doctors;
}
int visitors=0; //number of visitors in the room
int doctors=0; //number of doctors in the room
医生和访客(这个名为Friend的班级)是线程
public class Friend extends Thread{
public Friend(Room room_reference){
room=room_reference;
}
public void run(){
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
room.friendVisit();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
room.exitFriend();
}
private Room room; //reference to the room
这是医生的话:
public class Doctor extends Thread{
public Doctor(Room room_reference){
room=room_reference;
}
public void run(){
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
room.doctorVisit();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
room.exitDoctor();
}
private Room room; //reference to the room
这是一个显示线程,用于跟踪访客和医生的数量:
public class Display extends Thread{
public Display(Room room_reference){
room=room_reference;
}
public void run(){
while(true)
{
try {
sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("The room contains "+room.getDoctors()+
" doctors and "+room.getVisitors()+" visitors.");
}
}
private Room room;
这是我的主要内容:
public class Demo {
public static void main(String[]args){
Room room=new Room();
Friend friend=new Friend(room);
Doctor doctor=new Doctor(room);
Display display=new Display(room);
display.start();
while(true){
if(new Random().nextBoolean()==true){
friend=new Friend(room);
friend.start();
}
if(new Random().nextInt(5)==3){
doctor=new Doctor(room);
doctor.start();
}
}
}
问题是不止一个医生可以进入房间,我不明白为什么,因为Room类中的方法适用于访客。提前谢谢。
答案 0 :(得分:2)
我认为你的一个错误是假设wait()
只有在满足它的条件时才会返回:
if(doctors>0 || visitors>0)
wait();
您可以通过此wait()
语句返回if
语句中的条件为false。也许尝试一下while循环:
while (doctors>0 || visitors>0) {
wait();
}
(添加括号,当然,因为你知道缺少括号是evillll ..... )
可能还有其他问题 - 我还没有启动你的代码。