生产者消费者模式

在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程。在多线程开发
当中,如果生产者处理速度很快,而消费者处理速度很慢,那么生产者就必须等待消费者
处理完,才能继续生产数据。同样的道理,如果消费者的处理能力大于生产者,那么消费
者就必须等待生产者。为了解决这种生产消费能力不均衡的问题,所以便有了生产者和消
费者模式。

生产者/消费者模式的作用
- 支持并发
- 解耦
- 支持忙闲不均
编码体现 

public class Basket {
    private volatile Object obj = null; // 利用volatile保证可见性
 
    public synchronized void produce(Object obj) {
        while (this.obj != null) {
            try {
//                this.wait();// 当前线程进入minitor的waitSet中
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.obj = obj;
        this.notifyAll(); // 唤醒处于waitSet中的所有线程
        System.out.println("生产了一个对象:" + obj);
    }
 
    public synchronized void consume() {
        while (obj == null)
            try {
//                this.wait();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        System.out.println("消费了一个对象:" + obj);
        this.obj = null;
        this.notifyAll();
    }
}
public class Consumer implements Runnable {
    private Basket resource = null;
 
    public Consumer(Basket resource) {
        this.resource = resource;
    }
 
    public void run() {
        for (int i = 0; i < 20; i++) {
            resource.consume();
        }
    }
}
public class Producer implements Runnable {
    private Basket resource = null;
 
    public Producer(Basket resource) {
        this.resource = resource;
    }
 
    public void run() {
        for (int i = 0; i < 20; i++) {
            Object obj = new Date();
            resource.produce(obj);
        }
    }
}
public class Test {
    public static void main(String[] args) {
        Basket resource = new Basket();
        new Thread(new Producer(resource)).start();
        new Thread(new Consumer(resource)).start();
    }
}
wait和notify/notifyAll的用法
调用wait/notify之类的方法要求必须在当前线程对象内部,例如synchronized方法中 

- 当线程执行wait()时,会把当前的锁释放,然后让出CPU,进入等待状态。不能更改为sleep,因为sleep不会释放锁
- 当执行notify/notifyAll方法时,会唤醒一个处于等待该对象锁的线程,然后继续往下执行,直到执行完退出对象锁锁住的区域(synchronized修饰的代码块)后再释放锁。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值