前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >生产者和消费者

生产者和消费者

作者头像
汤高
发布2018-01-11 17:23:53
7370
发布2018-01-11 17:23:53
举报
文章被收录于专栏:积累沉淀

用到 wait()、notify()/notifyAll()方法

代码语言:javascript
复制
public class Test15 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        AppleBox ab=new AppleBox();
        Producer p=new Producer(ab);

        Consumer c=new Consumer(ab);
        Consumer cd=new Consumer(ab);

        new Thread(p).start();
        new Thread(c).start();
        new Thread(cd).start();


    }



}
//消息的对象=>消息
class Apple{
    int id;
    Apple(int id){
        this.id=id;
    }

    public String toString(){
        return "apple" +id;
    }

}
//容器
class AppleBox{
    int index=0;
    Apple[] apples=new Apple[5];

    public synchronized void deposite(Apple apple){
        while(index==apples.length){
            try {
                this.wait();    //wait是Object 对象的方法  =>将这个对象所在的线程阻塞住  释放对象锁
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
        }

        this.notifyAll();//notifyAll也是Object对象的方法  =>通知其他线程启动

        apples[index]=apple;
        index++;
    }

    public synchronized Apple withdraw(){
        while(index==0){
            try {
                this.wait();
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
        }

        this.notifyAll();


        index--;
        return apples[index];

    }


}

class Producer implements Runnable{
    AppleBox ab=null;

    Producer(AppleBox ab) {
        this.ab=ab;
    }

    @Override
    public void run() {
        for(int i=0;i<20;i++){
            Apple a=new Apple(i);
            ab.deposite(new Apple(i));
            System.out.println(Thread.currentThread().getName()+"生产了"+a);

            try {
                Thread.sleep((int)(Math.random()*1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}

class Consumer implements Runnable{

    AppleBox ab=null;
    public Consumer(AppleBox ab) {
        this.ab=ab;
    }

    @Override
    public void run() {
        for(int i=0;i<20;i++){
            Apple a=ab.withdraw();

            System.out.println(Thread.currentThread().getName()+"消费了"+a);

            try {
                Thread.sleep((int)(Math.random()*1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-11-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档