生产者与消费者模式
生产者消费者问题是一个多线程同步的经典问题,这个问题描述了生产者线程和消费者线程共享固定大小的缓冲区的问题。生产者不断的向缓冲区添加数据,消费者不断的消费缓冲区的数据,这个问题的关键是:
保证生产者在缓冲区满的时候不再向缓冲区添加数据,消费者在缓冲区空的时候也不会的时候消费缓冲区数据
解决思路:
- 生产者不断的生产,直到缓冲区满的时候,阻塞生产者线程,缓冲区不满的时候,继续生产
- 消费者不断的消费,直到缓冲区空的时候,阻塞消费者线程,缓冲区不空的时候,继续消费
使用wait,notify方式实现
public class ProducerAndConsumer {
//消费者
static class Consumer implements Runnable {
private List<Integer> queue;
public Consumer(List<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
System.out.println("Queue is Empty");
queue.wait();
}
int i = queue.remove(0);
queue.notifyAll();
System.out.println(Thread.currentThread().getName() + "消费了:" + i + "还剩:" + queue.size());
Thread.sleep(100);
}
}
} catch (InterruptedException e) {
}
}
}
//生产者
static class Producer implements Runnable {
private List<Integer> queue;
private int length; //容量
public Producer(List<Integer> queue, int length) {
this.queue = queue;
this.length = length;
}
@Override
public void run() {
try {
while (true) {
synchronized (queue) {
while (queue.size() > length) {
queue.wait();
}
queue.add(1