生产者与消费者-示例代码Java

本文介绍了一个简单的生产者与消费者模式示例,通过厨师(生产者)和服务员(消费者)的角色来展示这一经典并发编程模式。该模式使用了线程同步机制如synchronized关键字和wait/notify方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 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");
        }
    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值