多线程生产者消费者 蒸笼窝头

25 篇文章 1 订阅
5 篇文章 0 订阅
//多线程生产者消费者 蒸笼窝头
public class  ProducerConsumer{
    public static void main(String[] args)  {
        SyncStack ss = new SyncStack();//实例化一个堆栈蒸笼
        Producer p = new Producer(ss);//实例化生产者,参数用同一个蒸笼ss
        Consumer c = new Consumer(ss);//实例化消费者,参数用同一个蒸笼ss
        new Thread(p).start();//开1个线程 生产者p,调用start()方法
        new Thread(c).start();//开1个线程 消费者c,调用start()方法
    }
}

class Wotou{ //自定义窝头类
    int id;
    Wotou(int id)   {
        this.id = id;
    }
    //重写toString
    public String toString(){
        return "WoTou:" + id;
    }
}

class SyncStack{//自定义的堆栈类,就是蒸笼
    int index = 0;//序数,第几个,初始化为0
    Wotou[] arrWT = new WoTou[6];// 数组 Type[] arrName = new Type[];

    public synchronized void push(WoTou wt) {  //push进入堆栈 进站方法
        while (index == arrWT.length){ //堆栈 蒸笼 满了 用while不用if 就不会catch了异常就跳出if语句
            try {
                this.wait;//访问并锁定此对象的线程wait 
            }catch (InterruptedException e){
                e.printStackTrace();//打印错误站
            }           
        }
        this.notify();//唤醒另一个线程 消费者
        arrWT[index] = wt;//存入元素 到数组里 窝头
        index ++;//序数后++
    }

    public synchronized  WoTou pop(){ //出站方法
        while(index == 0){
        try {
            this.wait;//访问并锁定此对象的线程wait 
            }catch (InterruptedException e){
                e.printStackTrace();//打印错误站
            }   
    }
    this.notify();//唤醒另一个线程 生产者
    index --;//序数先--
    return arrWT[index];//取出元素 窝头
    }
}

class Producer implements Runnable{ //生产者 厨师 线程

    SyncStack ss = null;//生产者必须持有目的地的引用 蒸笼 ,实例化一个堆栈蒸笼
    Producer(SyncStack ss){
        this.ss = ss;
    }

    public void run(){
        for (int i = 0;i<20 ;i++ )  {
            WoTou wt = new WoTou(i);//实例化 序号窝头
            ss.push(wt);//调用堆栈蒸笼进站方法
            System.out.println("生产了:"+wt);
            try {
                Thread.sleep((int)(Math.random()*1000));//执行一次,睡眠1下,让其他线程执行
            }
            catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable{//消费者 客人 线程
    SyncStack ss = null;//必须持有目的地的引用 蒸笼 ,实例化一个堆栈蒸笼
    Consumer(SyncStack ss){
        this.ss = ss;
    }

    public void run(){
        for (int i = 0;i<20 ;i++ )  {
            WoTou wt = ss.pop();//调用堆栈蒸笼ss出站方法  返回值 是 序号窝头
            System.out.println("消费了:"+wt);
            try {
                Thread.sleep((int)(Math.random()*1000));//执行一次,睡眠1下,让其他线程执行,math 是double要强转int
            }
            catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值