`
zhaohong
  • 浏览: 59255 次
  • 性别: Icon_minigender_1
  • 来自: 郑州
社区版块
存档分类
最新评论

java实现生产者消费者算法

阅读更多
public class testProducerConsumer {

	public static void main(String[] args) {
		ProductContainer pc = new ProductContainer();
		Producter producter = new Producter(pc);
		Consumer consumer = new Consumer(pc);
		new Thread(producter).start();
		new Thread(consumer).start();
	}

}

class Product {
	private int ID;

	Product(int ID) {
		this.ID = ID;
	}

	public String toString() {
		return "Product:" + ID;
	}
}

class ProductContainer {
	int index = 0;
	Product[] product = new Product[10];

	public synchronized void push(Product pro) {
		while (index == product.length) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		product[index] = pro;
		index++;
	}

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

class Producter implements Runnable {

	ProductContainer pc = null;

	Producter(ProductContainer pc) {
		this.pc = pc;
	}

	public void run() {
		for (int i = 0; i < 50; i++) {
			Product p = new Product(i);
			pc.push(p);
			System.out.println("生产了:" + p);
			try {
				Thread.sleep((int)(Math.random() * 1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class Consumer implements Runnable {
	ProductContainer pc = null;

	Consumer(ProductContainer pc) {
		this.pc = pc;
	}

	public void run() {
		for (int i = 0; i < 50; i++) {
			Product pro = pc.pop();
			System.out.println("消费了:" + pro);
			try {
				Thread.sleep((int)(Math.random() * 1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics