java多线程-生产者消费者经典问题

生产者消费者经典问题


生产者和消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一个存储空间,如下图所示,生产者向空间里存放数据,而消费者取用数据,如果不加以协调可能会出现以下情况:

生产者消费者图

  存储空间已满,而生产者占用着它,消费者等着生产者让出空间从而去除产品,生产者等着消费者消费产品,从而向空间中添加产品。互相等待,从而发生死锁。




public class Test {
	public static void main(String[] args) {
		Container arr = new Container(20);
		Producer p = new Producer(arr);
		Custromer c = new Custromer(arr);
		new Thread(p).start();
		new Thread(c).start();
	}
}

class Container {
	private int index = 0;
	private int size;
	private Object[] arr = null;

	public int size() {
		return size;
	}

	public Container(int size) {
		this.size = size;
		arr = new Object[size];
	}

	public synchronized void push(Object o) {
		while (index == size) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		arr[index] = o;
		index++;
		this.notifyAll();
	}

	public synchronized Object pop() {
		while (index == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		index--;
		return arr[index];
	}
}

class Producer implements Runnable {

	private Container arr = null;

	public Producer(Container arr) {
		this.arr = arr;
	}

	public void run() {
		int index = 0;
		while (index < 100) {
			arr.push(new Object());
			System.out.println("生产了一个++++++");
			index++;
		}
	}
}

class Custromer implements Runnable {
	private Container arr = null;

	public Custromer(Container arr) {
		this.arr = arr;
	}

	public void run() {
		int index = 0;
		while (index < 100) {
			arr.pop();
			System.out.println("消费了一个-------");
			index++;
		}
	}
}


你可能感兴趣的:(java,java源码解析)