加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java多线程示例 模拟生产者消费者

发布时间:2020-05-24 15:48:15 所属栏目:Java 来源:互联网
导读:java多线程示例 模拟生产者消费者

下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。

脚本之家小编现在分享给大家,也给大家做个参考。

public class ProducerConsumer {

    public static void main(String[] args) {
        SyncStack ss=new SyncStack();
        Producer pro=new Producer(ss);
        Consumer con=new Consumer(ss);
        new Thread(pro).start();
        new Thread(pro).start();
        new Thread(con).start();

    }

}
class Product{
    int id;
    public Product(int id){
        this.id=id;
    }
    public String toString(){//重写toString 方法,给pro加上编号,以便调试
        return "product   "+id;
    }
}
class SyncStack{//栈,先进后出
    Product[] proArr=new Product[6];//定义容器只能装6件产品
    int index=0;
    public synchronized void push(Product pro){
        while(index==proArr.length){//当容器装满了产品,暂停生产
            try{
                this.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.notifyAll();//唤醒消费者消费
        proArr[index]=pro;
        index++;

    }
    public synchronized Product pop(){//同步,确保不被打断
        while(index==0){//当容器里没有产品可消费,暂停消费
            try{
                this.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.notifyAll();//唤醒生产者生产
        index--;
        return proArr[index];
    }
}
class Producer implements Runnable{
    SyncStack ss=null;
    public Producer(SyncStack ss){
        this.ss=ss;
    }
    public void run() {
        for(int i=0;i<20;i++){
            Product pro=new Product(i);
            ss.push(pro);
            System.out.println("生产了:"+pro);
            try{//方便观察结果,没有实际意义
                Thread.sleep((int)(Math.random()*200));
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
class Consumer implements Runnable{
    SyncStack ss=null;
    public Consumer(SyncStack ss){
        this.ss=ss;
    }
    public void run(){
        for(int i=0;i<20;i++){
            Product pro=ss.pop();
            System.out.println("消费了:"+pro);
            try{//方便观察结果,没有实际意义
                Thread.sleep((int)(Math.random()*1000));
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读