Java实现有201颗豆子,有4个人:小红,小明,小强,小林,请将豆子按每次1人1颗的分,直到201颗豆子分完,请找出分到豆子最多得那个人 提示:使用多线程 + 可重入互斥锁来完成
时间: 2023-10-24 11:07:43 浏览: 139
以下是Java实现的示例代码:
```java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class DivideBeans {
private static int beans = 201;
private static int maxBeans = 0;
private static String maxName = "";
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Thread redThread = new Thread(new DivideBeanThread(lock, "小红"));
Thread mingThread = new Thread(new DivideBeanThread(lock, "小明"));
Thread qiangThread = new Thread(new DivideBeanThread(lock, "小强"));
Thread linThread = new Thread(new DivideBeanThread(lock, "小林"));
redThread.start();
mingThread.start();
qiangThread.start();
linThread.start();
try {
redThread.join();
mingThread.join();
qiangThread.join();
linThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("分到豆子最多的人是:" + maxName + ",豆子数量为:" + maxBeans);
}
private static class DivideBeanThread implements Runnable {
private Lock lock;
private String name;
public DivideBeanThread(Lock lock, String name) {
this.lock = lock;
this.name = name;
}
@Override
public void run() {
while (true) {
lock.lock();
try {
if (beans > 0) {
beans--;
System.out.println(name + "分到了1颗豆子,还剩" + beans + "颗豆子");
if (beans == 0) {
System.out.println(name + "分到了最后1颗豆子");
}
if (beans == maxBeans) {
maxName = maxName.equals("") ? name : maxName + "和" + name;
maxBeans = beans;
} else if (beans > maxBeans) {
maxName = name;
maxBeans = beans;
}
} else {
break;
}
} finally {
lock.unlock();
}
}
}
}
}
```
该程序使用了一个静态变量 `beans` 来表示剩余的豆子数量,使用了一个可重入互斥锁 `ReentrantLock` 来实现多线程同步。程序启动四个线程,每个线程不断获取互斥锁,尝试从剩余豆子数量中分配1颗豆子,如果成功则将分配结果打印到控制台,并更新分到豆子最多的人的信息。
程序运行结束后,将输出分到豆子最多的人的姓名和豆子数量。
阅读全文