我有这个练习,一种医院模拟,我必须控制对每个单独房间的访问。医生可以一次进入房间,并且只有在没有访客的情况下才能进入。相反,访客只能在没有医生且最多 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
医生和访客(它称为朋友的类)是线程
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 类中的方法适用于访客。提前致谢。