多线程11生产者消费者

代码

生产者

public class PushTarget implements Runnable{
    Tmall tmall;
    public PushTarget(Tmall tmall){
        this.tmall = tmall;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            tmall.push();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

消费者

public class TakeTarget implements Runnable{    
    Tmall tmall;
    public TakeTarget(Tmall tmall){
        this.tmall = tmall;
        
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            tmall.take();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

Tmall

public class Tmall {

    int count;
    
    public final int MAX_COUNT=10;
    
    public synchronized void push(){
//      用while防止叫醒后执行count++
        while (count >= MAX_COUNT) {
//          达到10,生产者停止生产,生产线程等待
            System.out.println("达到10,生产者停止生产");
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        count++;
        System.out.println("生产者,目前库存"+count);
//      生产完后通知等待的消费者线程
        notifyAll();
    }
    
    public synchronized void take(){
        
        while (count<=0) {
//          达到0,库存不够,消费线程等待
            System.err.println("库存不够");
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        count--;
        System.err.println("消费后剩余"+count);
//      消费后通知等待的生产线程
        notifyAll();
        
    }
}

测试

public class Main {

    public static void main(String[] args) {
        Tmall tmall = new Tmall();
        TakeTarget t = new TakeTarget(tmall);
        PushTarget p = new PushTarget(tmall);
        new Thread(p).start();
        new Thread(p).start();
        new Thread(p).start();
        new Thread(p).start();
        
        new Thread(t).start();
        new Thread(t).start();
        new Thread(t).start();
//      new Thread(t).start();  
    }   
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容