线程 ---- 锁(生产者、消费者)

本文通过具体示例解析了Java中生产者消费者模式的实现方式,重点介绍了如何使用synchronized关键字来确保线程同步,以及如何利用wait和notify方法解决生产者与消费者之间的资源竞争问题。

Java经典面试题 -----  生产者消费者

/**
 * 生产者 消费者问题
 * 解释 : wait notify 方法
 * sleep 与 wait的区别
 * 线程锁机制
 */
public class ProducerConsumer {
    public static void main(String[] args) {
        SyncStack ss = new SyncStack();
        Producer p = new Producer(ss);
        Consumer c = new Consumer(ss);
        
        new Thread(p).start();
        new Thread(c).start();
    }
}

class MT{
    int id ;
    MT(int id){
        this.id = id;
    }
    
    public String toString(){
        return "MT:" + id;
    }
}

class SyncStack {
    int index = 0 ;
    MT[] mts = new MT[6];
    
    public synchronized void push (MT mt){
        if(index == mts.length){
            try {
                this.wait();
            }catch(InterruptedException ex){
                ex.printStackTrace();
            }
        }
        this.notify();
        mts[index] = mt;
        index ++;
    }
    
    public synchronized MT pop(){
        if(index == 0){
            try {
                this.wait();
            }catch(InterruptedException ex){
                ex.printStackTrace();
            }
        }
        this.notify();
        index -- ;
        return mts[index];
    }
}

class Producer implements Runnable{
    SyncStack stack = null;
    
    public Producer(SyncStack stack) {
        this.stack = stack;
    }
    public void run(){
        for(int i = 0 ; i < 20 ; i ++){
            MT mt = new MT(i);
            stack.push(mt);
            System.out.println("生产了:" + mt);
            try{
                Thread.sleep((int)(Math.random()*200));
            }catch(InterruptedException ex){
                ex.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable{
    
    SyncStack stack = null;
    
    public Consumer(SyncStack stack) {
        this.stack = stack;
    }
    
    public void run(){
        for(int i = 0 ; i < 20 ; i ++){
            MT mt = stack.pop();
            System.out.println("消费了:" + mt);
            try{
                Thread.sleep((int)(Math.random()*1000));
            }catch(InterruptedException ex){
                ex.printStackTrace();
            }
        }
    }
}

转载于:https://www.cnblogs.com/xuewuzhijing95hao/p/7127118.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值