Java复习之生产者消费者案例

这篇博客主要是通过模拟生活中的生产者消费者的案例,来进一步熟悉线程的相关操作。

/**
 * 生产者---厨师
 */
class Productor implements Runnable {
    private Food food;

    public Productor(Food food) {
        this.food = food;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                food.set("韭菜炒鸡蛋","男人的好食品,多吃有益健康");
            } else {
                food.set("葱爆腰花","补肾气,通膀胱,我好她也好");
            }
        }
    }
}
/**
 * 消费者---服务员
 */
class Consumer implements Runnable
{
    private Food food;
    public Consumer(Food food)
    {
        this.food=food;
    }
    @Override
    public void run() {
        for (int i=0;i<100;i++){
           food.get();
        }
    }
}
/**
 * 产品---食物
 */
class Food{
    private String name;
    private String content;
    //标记变量
    private boolean flag=true;
    //true表示可以生产,false表示可以消费
    public synchronized void set(String name,String concent)
    {
        if(!flag)
        {
            try {
                this.wait();//让当前线程进入等待池等待,没有指定时间,
                            // 需要其它线程唤醒,释放对象锁,让出CPU
                            //sleep释放CPU,不释放对象锁住
            } catch (InterruptedException ex)
            {
                ex.printStackTrace();
            }
        }
        this.setName(name);
        try {
            Thread.sleep(300);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        this.setContent(concent);
        flag=false;//表示可以消费
        this.notify();//唤醒在该监视器上的一个线程
    }
    //消费产品
    public synchronized void get()
    {
        if(flag)
        {
            try {
                this.wait();
            }catch (InterruptedException ex)
            {
                ex.printStackTrace();
            }
        }
        try {
            Thread.sleep(300);
        }catch (InterruptedException ex)
        {
            ex.printStackTrace();
        }
        System.out.println(this.getName()+":"+this.getContent());
        flag=true;
        this.notify();
    }

    public Food() {
    }
    public Food(String name, String content) {
        this.name = name;
        this.content = content;
    }

    public String getName() {
        return name;
    }

    public String getContent() {
        return content;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setContent(String content) {
        this.content = content;
    }
    @Override
    public String toString() {
        return "Food{" +
                "name='" + name + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}
public class ThreadDemo {
    public static void main(String args[])
    {
        Food food=new Food();
        Productor productor=new Productor(food);
        Consumer consumer=new Consumer(food);
        new Thread(productor).start();
        new Thread(consumer).start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package producer; import java.util.Vector;//输入java矢量 class SyncStack {//实现堆栈功能,不能同时读写 private Vector buffer//私人接口向量缓冲区 = new Vector //新建向量 (400,200); char contents; private boolean ava=false; public synchronized char get() {//出栈 while (ava==false) //如果生产者还没有产生字符就一直等待 { try { this.wait(); } catch (InterruptedException e)//当线程在活动之前或活动期间处于正在等待、休眠或占用状态且该线程被中断时,抛出该异常 { e. printStackTrace(); } } ava=false; notifyAll(); return contents; } public synchronized void push(char c) { while(ava==true){ try { wait(); } catch (InterruptedException e) { // TODO 自动生成 catch 块 e.printStackTrace(); } }//入栈 ava=true; this.notify();//通知其它线程把数据出栈 Character charObj = new Character(c); buffer.addElement(charObj); contents=c; } public void print(char c) { // TODO 自动生成方法存根 } } class ControlEnter {//每行输出结果的个数 public static int count = 0; void counter() { count++; if(count ==5) { System.out.println(); count = 0; } } } class Producer implements Runnable {//生产者类 private SyncStack theStack;//生产者类获得的字符都来自同步堆栈 private ControlEnter controlenter; public Producer (SyncStack s,ControlEnter ce) { theStack = s; controlenter = ce; } public void run() { char c; for (int i = 0; i < 30; i++) { c = (char)(Math.random() * 26 + 'a');//随机产生30个小写字母 theStack.push(c);//存入堆栈 System.out.print("生产者产生: " + c +" "); controlenter.counter( ); try { Thread.sleep//线程休眠 ((int)(Math.random() * 200));//以0~200ms的速度随机 } catch (InterruptedException e) //当线程在活动之前或活动期间处于正在等待、休眠或占用状态且该线程被中断时,抛出该异常 { e.printStackTrace( ); } } } } class Consumer implements Runnable {//消费者类 private SyncStack theStack;//消费者类获得的字符都来自同步堆栈 private ControlEnter controlenter; public Consumer (SyncStack s,ControlEnter ce) { theStack = s; controlenter = ce; } public void run() { char value; for (int i=0; i < 30; i++) {//从堆栈中取数,并输出 value = theStack.get();//取出生产者产生的字母 System.out.print("消费者消费: " + value+" ");//消费者输出 controlenter.counter( ); try { Thread.sleep((int) (Math.random() * 2000));//控制取数的速度:0~2s/*每读取一个字符线程就睡眠*/ } catch (InterruptedException e)//当线程在活动之前或活动期间处于正在等待、休眠或占用状态且该线程被中断时,抛出该异常 { e.printStackTrace(); } } } } public class B {//主线程总调度 public static void main(String []args) { ControlEnter ce = new ControlEnter(); SyncStack stack = new SyncStack();//下面的消费者类对象和生产者类对象所操作的是同一个同步堆栈对象 Producer p1 = new Producer(stack,ce); new Thread(p1).start();//生产者线程启动 Consumer c1 = new Consumer(stack,ce); new Thread(c1).start();//消费者线程启动 } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值