一个房间五十个人有四个门四个门相互独立一个门同时只能进或者出。用java怎么实现
可以使用Java中的线程来实现这个房间的进出控制。具体实现如下:
-
定义一个Room类,包含一个计数器count,表示当前房间内的人数。
-
定义一个Person类,实现Runnable接口,表示一个人的进出行为。Person类包含一个Room对象和一个boolean变量isEnter,表示当前这个人是进入房间还是离开房间。
-
在Person类中重写run()方法,在run()方法中根据isEnter变量的值调用Room对象的enter()或leave()方法,进入或离开房间。
-
在Room类中定义enter()和leave()方法,用于控制房间内人数的增减。enter()方法中先检查当前房间内的人数是否已满,如果已满则等待;否则将计数器加一,并输出当前房间内的人数。leave()方法同理,先检查当前房间内的人数是否为零,如果为零则等待;否则将计数器减一,并输出当前房间内的人数。
-
在主程序中创建一个Room对象和50个Person对象,然后将这些Person对象分别放到四个线程中执行。
代码实现如下:
Room类:
public class Room { private int count = 0; private final int MAX_COUNT = 50;
public synchronized void enter() {
while (count >= MAX_COUNT) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count++;
System.out.println("Enter: " + count);
notifyAll();
}
public synchronized void leave() {
while (count <= 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
System.out.println("Leave: " + count);
notifyAll();
}
}
Person类:
public class Person implements Runnable { private Room room; private boolean isEnter;
public Person(Room room, boolean isEnter) {
this.room = room;
this.isEnter = isEnter;
}
@Override
public void run() {
if (isEnter) {
room.enter();
} else {
room.leave();
}
}
}
主程序:
public class Main { public static void main(String[] args) { Room room = new Room(); Thread[] threads = new Thread[4]; for (int i = 0; i < 50; i++) { Person person = new Person(room, i % 2 == 0); int index = i % 4; if (threads[index] == null) { threads[index] = new Thread(person); } else { threads[index].start(); threads[index] = null; } } } }
原文地址: https://www.cveoy.top/t/topic/bae4 著作权归作者所有。请勿转载和采集!