#牛客在线求职答疑中心#个淋浴间,每个淋浴间最多同时进2个人,同淋浴间不允许出现男女混浴,每人用时10分钟,
现有10个男生和10个女生需要洗浴, 请用多线程实现
现有10个男生和10个女生需要洗浴, 请用多线程实现
全部评论
这个问题有点复杂,涉及到多线程和同步的问题。
首先,我们需要创建一个表示淋浴间的类,每个淋浴间都是一个线程。然后,我们需要一个队列来存储等待洗浴的人。当有人进入淋浴间时,我们需要检查是否有人在等待,如果有,就唤醒他们。最后,我们需要一个计时器来确保每个人在10分钟后离开淋浴间。
以下是一个可能的实现:
```java
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class Shower {
private static final int CAPACITY = 2;
private static final int TIME_LIMIT = 10;
private static final TimeUnit TIME_UNIT = TimeUnit.MINUTES;
private final LinkedBlockingQueue<Person> queue = new LinkedBlockingQueue<>();
private final Thread thread = new Thread(this::run);
public Shower() {
thread.start();
}
public void join() throws InterruptedException {
thread.join();
}
private void run() {
while (true) {
try {
Person person = queue.take();
synchronized (this) {
if (queue.size() == CAPACITY) {
wait();
} else {
System.out.println(person + "进入了淋浴间");
queue.add(person);
notifyAll();
}
}
TimeUnit.MILLISECONDS.sleep(TIME_LIMIT * 60 * 1000);
synchronized (this) {
queue.remove(person);
System.out.println(person + "离开了淋浴间");
if (queue.isEmpty()) {
wait();
} else {
notifyAll();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
Shower shower = new Shower();
for (int i = 0; i < 10; i++) {
show
相关推荐


招联金融
| 实习
| 超多精选岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享

点赞 评论 收藏
分享