package org.jaychang.corejava.review;java
import java.util.LinkedList;
import java.util.List;this
/**
* @title <p>生產者與消費者</p>
* @author Jay Chang
* @date 2009/11/09
*/
class Stack {
private List<Object> list = new LinkedList<Object>();.net
/**
* 出棧
*
* @return
*/
public Object pop() {
return list.remove(list.size() - 1);
}線程
/**
* 將元素壓入棧
*
* @param obj
*/
public void push(Object obj) {
list.add(list.size(), obj);
}對象
public int size() {
return list.size();
}
}rem
/**
*
* @author Jay Chang
*
*/
class Producer extends Thread {
private Stack stack;get
public Stack getStack() {
return stack;
}同步
/**
*
* @param stack
*/
public void setStack(Stack stack) {
this.stack = stack;
}it
/**
* 生產者生產商品,當商品棧滿時,通知消費者消費商品
*/
public void produce() {
for (int i = 0; i < 100; i++) {
// 同步stack
synchronized (stack) {
System.out.println("producer get the lock");io
//這裏指定存放商品的商品棧的最大容量爲10
while (stack.size() == 10) {
try {
//將生產者線程持有stack對象的鎖釋放,並將生產者線程放到stack對象的等待池中
stack.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 模擬生產者生產商品過程所需的時間
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String goods = "goods" + stack.size();
//將生產的商品放到存放商品的商品棧中
stack.push(goods);
System.out.println("producer product " + goods);
//喚醒在stack對象等待池中的等待的全部線程
stack.notifyAll();
}
}
}
public void run() {
produce();
}
}
class Consumer extends Thread {
private Stack stack;
public Stack getStack() {
return stack;
}
public void setStack(Stack stack) {
this.stack = stack;
}
/**
*
* 消費者消費商品,當商品棧中爲空時通知生產者生產商品
*/
public void consume() {
for (int i = 0; i < 100; i++) {
synchronized (stack) {
System.out.println("consumer get the lock");
while (stack.size() == 0) {
try {
stack.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 模擬消費者消費商品,所需的時間
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Object obj = stack.pop();
System.out.println("cosumer consume " + obj);
}
}
}
public void run() {
consume();
}
}
public class Test{
public static void main(String[] args) {
Stack stack = new Stack();
Consumer consumer = new Consumer();
consumer.setStack(stack);
Producer producer1 = new Producer();
producer1.setStack(stack);
Producer producer2 = new Producer();
producer2.setStack(stack);
consumer.start();producer1.start();producer2.start();
} }