我有這個練習,一種醫院模擬,我必須控制對每個單數房間的訪問。醫生可以一次進入房間,並且只有在沒有訪客進入時才能進入房間。相反,如果沒有醫生進入房間並且最多有4位訪客進入,則訪問者只能進入房間。以下是我的代碼:Java - 使用同步方法的多線程練習
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
這裏有一個顯示線程保持訪問人數的痕跡ORS和醫生:
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();
}
}
}
的問題是,不止一個醫生可以進入房間,我不明白爲什麼,因爲在客房類中的方法爲參觀者工作。提前致謝。
你試過調試嗎?此外,你永遠不會開始你實例化的初始朋友和醫生。 – Taylor