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

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

发布时间:2020-12-15 00:15:48 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 public class ProducerConsumer { public static void main(String[] args) { SyncStack ss=new SyncStack(); Producer pro=new Producer(ss); Consum

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

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();
            }
        }
    }
}

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

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

    推荐文章
      热点阅读