/**
* Copyright (C), 2018-2019, LMaWC
* FileName: Restaurant
* Author: neo
* Date: 2019/3/19 16:06
* Description: 生产者与消费者示例
* History:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package com.neo;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* 〈一句话功能简述〉<br>
* 〈生产者与消费者示例〉
*
* @author neo
* @create 2019/3/19
* @since 1.0.0
*/
public class Restaurant {
// 餐馆里应该有什么
Meal meal;
Chef chef = new Chef(this);
WaitPerson waitPerson = new WaitPerson(this);
ExecutorService exec = Executors.newCachedThreadPool();
public Restaurant(){
exec.execute(chef);
exec.execute(waitPerson);
}
public static void main(String[] args) {
new Restaurant();
}
}
// 消费对象(一顿饭)
class Meal{
private final int orderNum;
public Meal(int orderNum){
this.orderNum=orderNum;
}
@Override
public String toString() {
return "Meal "+ orderNum;
}
}
//消费者(服务员)1.创建需求2.向生产者请求食物
class WaitPerson implements Runnable{
private Restaurant restaurant;
public WaitPerson(Restaurant r){
restaurant = r;
}
public void run() {
try {
while (!Thread.interrupted()){
synchronized (this){
while (restaurant.meal ==null){
wait();
}
}
System.out.println("WaitPerson got "+ restaurant.meal);
synchronized (restaurant.chef){ // 获取厨师的锁,通过初始的锁
restaurant.meal = null;
restaurant.chef.notifyAll();
}
}
}catch (InterruptedException e) {
System.out.println("WaitPerson interrupted");
}
}
}
// 生产者(厨师)1.提供需求2.等待消费者请求食物
class Chef implements Runnable{
private Restaurant restaurant;
private int count = 0;
public Chef(Restaurant r){
restaurant = r;
}
public void run() {
try {
while (!Thread.interrupted()){
synchronized (this){
while (restaurant.meal != null){
wait();
}
}
if(++count == 10){ // 只做10份,count从0到9
System.out.println("Out of food, closing");
// 关闭所有线程
restaurant.exec.shutdownNow();
}
System.out.println("Order up!");
synchronized (restaurant.waitPerson){
restaurant.meal = new Meal(count); // 生产一顿饭
restaurant.waitPerson.notifyAll();
}
TimeUnit.MILLISECONDS.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Chef interrupted");
}
}
}