java - 生产者消费者 运行只生产不消费?求大神指点一二三四
PHPz
PHPz 2017-04-18 10:26:35
[Java讨论组]
public class ProducerConsumer {
    public static void main(String[] args) {
        LZ a = new LZ();
        Producer b1 = new Producer(a);
        Consumer c = new Consumer(a);
        new Thread(c).start();    
        new Thread(b1).start();                
    }
}
class MT{
    int id = 0;
    MT(int id) {
        this.id = id;
    }
    public String toString(){
        return "馒头:"+id;
    }
}
class LZ{
    MT[] arrmt = new MT[6];
    int index = 0;
}
class Producer implements Runnable{
    LZ z =null;
    Producer(LZ l){
        z = l;
    }
    public synchronized void push(LZ z){
        for(int i=0; i<20; i++){
            while(z.index == z.arrmt.length){
                try{
                    this.wait();                
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
            this.notify();
            MT m= new MT(i);
            z.arrmt[z.index] = m;
            z.index++;
            System.out.println("生产"+m);
            try{
                Thread.sleep(500);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    public void run(){
        push(z);    
    }
}
class Consumer implements Runnable{
    LZ z =null;
    Consumer(LZ l){
        z = l;
    }    
    public synchronized void pop(LZ z){
        for(int i=0; i<20; i++){
            while(z.index == 0){
                try{
                    this.wait();                
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
            this.notify();
            z.index--;
            System.out.println("消费"+z.arrmt[z.index]);
            try{
                Thread.sleep(500);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    public void run(){
        pop(z);    
    }    
}

PHPz
PHPz

学习是最好的投资!

全部回复(1)
阿神

消费者启动时z.index就是0,这里自然就让线程进入等待中了。

while(z.index == 0){
    try{
        this.wait();                
    }catch(InterruptedException e){
        e.printStackTrace();
    }
}

而你的notify调用老是对自己进行,这有什么用……能运行这行代码,表示现在就不在等待中,反之,等待中的线程也不会运行这段代码。

this.notify();
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号