Java-使用同步方法的多线程练习
我有这个练习,一种医院模拟,我必须控制每个房间的入口。医生一次只能进入一个房间,只有在没有访客的情况下才能进入。相反,只有在没有医生且最多有4名访客进入的情况下,访客才能进入房间。这是我的密码:Java-使用同步方法的多线程练习,java,multithreading,synchronized,Java,Multithreading,Synchronized,我有这个练习,一种医院模拟,我必须控制每个房间的入口。医生一次只能进入一个房间,只有在没有访客的情况下才能进入。相反,只有在没有医生且最多有4名访客进入的情况下,访客才能进入房间。这是我的密码: public class Room { public Room(){ } public synchronized void friendVisit() throws InterruptedException{ if(visitors>4 || doctors>0)
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();
}
}
}
问题是不止一个医生可以进入这个房间,我不明白为什么,因为房间课程的方法对来访者有效。提前感谢。我认为您的一个错误是假设
wait()
只有在满足上述条件时才会返回:
if(doctors>0 || visitors>0)
wait();
如果语句为false,您可以从此调用返回到wait()
,条件在语句中。也许可以尝试一下while循环:
while (doctors>0 || visitors>0) {
wait();
}
(当然,添加括号,因为您知道缺少括号是很糟糕的……)
可能还有其他问题-我还没有启动您的代码。您尝试过调试吗?而且,你从来没有开始你实例化的最初的朋友和医生。是的,看起来你是完全正确的,这也是有道理的。非常感谢你,伙计。