//package number27;
import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Meal
{
private final int orderNum;
public Meal(int orderNum) { this.orderNum = orderNum; }
public String toString() { return "Meal " + orderNum; }
}
class WaitPerson implements Runnable
{
private Restaurant restaurant;
public WaitPerson(Restaurant r) { restaurant = r; }
public Lock lock = new ReentrantLock();
public Condition condition=lock.newCondition();
public void run()
{
try
{
while(!Thread.interrupted())
{
lock.lock();
try
{
while(restaurant.meal == null)
condition.await(); // ... for the chef to produce a meal
}
finally
{
lock.unlock();
}
System.out.println("Waitperson got " + restaurant.meal);
restaurant.chef.lock.lock();
try
{
restaurant.meal = null;
restaurant.chef.condition.signalAll();
}
finally
{
restaurant.chef.lock.unlock();
}
}
}
catch(InterruptedException e)
{
System.out.println("WaitPerson interrupted");
}
}
}
class Chef implements Runnable
{
private Restaurant restaurant;
private int count = 0;
public Chef(Restaurant r) { restaurant = r; }
public Lock lock = new ReentrantLock();
public Condition condition=lock.newCondition();
public void run()
{
try
{
while(!Thread.interrupted())
{
lock.lock();
try
{
while(restaurant.meal != null)
condition.await(); // ... for the meal to be taken
}
finally
{
lock.unlock();
}
if(++count == 10)
{
System.out.println("Out of food, closing");
restaurant.exec.shutdownNow();
}
System.out.println("Order up! ");
restaurant.waitPerson.lock.lock();
try
{
restaurant.meal = new Meal(count);
restaurant.waitPerson.condition.signalAll();
}
finally
{
restaurant.waitPerson.lock.unlock();
}
TimeUnit.MILLISECONDS.sleep(100);
}
}
catch(InterruptedException e)
{
System.out.println("Chef interrupted");
}
}
}
public class Restaurant
{
Meal meal;
ExecutorService exec = Executors.newCachedThreadPool();
WaitPerson waitPerson = new WaitPerson(this);
Chef chef = new Chef(this);
public Restaurant()
{
exec.execute(chef);
exec.execute(waitPerson);
}
public static void main(String[] args)
{
new Restaurant();
}
}
Thinking in java部分答案
需积分: 0 186 浏览量
2009-01-01
12:39:31
上传
评论
收藏 20KB RAR 举报
tomorrowforever
- 粉丝: 3
- 资源: 12
最新资源
- 适用于tensorflow-2.11.0 CUDA版本11.2的cuDNN8.1版本
- 5Y study学习平台2016计算机基础-综合测试(8)_哔哩哔哩_bilibili_2580252704.mp4
- (大赛作品)STM32实现的F072RB NUCLEO智能家居控制.zip
- STM32实现的数字示波器源码+数字信号处理教程、配套实例.zip
- 【cookie续续】【cookie续续】【cookie续续】
- 低功耗STM32实现的F411开发板(原理图+PCB源文件+官方例程+驱动等).zip
- 基于stm32实现的 nucleo-L476的智能灯(操作说明+源码).zip
- 基于STM32实现的 NUCLEO板设计彩色LED照明灯(纯cubeMX开发).zip
- 基于STM32实现的 的联合调试侦听设备解决方案(原理图、PCB源文件、调试工具、视频).zip
- 基于STM32实现的 人群定位、调速智能风扇设计(程序、设计报告、视频演示).zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈