package rejava
review;
import javautilLinkedList;
import javautilList;
/**
*
* @author Jay Chang
*
*/
class Stack {
private List<Object> list = new LinkedList<Object>()
/**
* 出栈
*
* @return
*/
public Object pop() {
return listremove(listsize() )
}
/**
* 将元素压入栈
*
* @param obj
*/
public void push(Object obj) {
listadd(listsize() obj)
}
public int size() {
return listsize()
}
}
/**
*
* @author Jay Chang
*
*/
class Producer extends Thread {
private Stack stack;
public Stack getStack() {
return stack;
}
/**
*
* @param stack
*/
public void setStack(Stack stack) {
thisstack = stack;
}
/**
* 生产者生产商品当商品栈满时通知消费者消费商品
*/
public void produce() {
for (int i = ; i < ; i++) {
// 同步stack
synchronized (stack) {
Systemoutprintln(producer get the lock)
//这里指定存放商品的商品栈的最大容量为
while (stacksize() == ) {
try {
//将生产者线程持有stack对象的锁释放并将生产者线程放到stack对象的等待池中
stackwait()
} catch (InterruptedException e) {
eprintStackTrace()
}
}
// 模拟生产者生产商品过程所需的时间
try {
Threadsleep()
} catch (InterruptedException e) {
eprintStackTrace()
}
String goods = goods + stacksize()
//将生产的商品放到存放商品的商品栈中
stackpush(goods)
Systemoutprintln(producer product + goods)
//唤醒在stack对象等待池中的等待的所有线程
stacknotifyAll()
}
}
}
public void run() {
produce()
}
}
class Consumer extends Thread {
private Stack stack;
public Stack getStack() {
return stack;
}
public void setStack(Stack stack) {
thisstack = stack;
}
/**
*
* 消费者消费商品当商品栈中为空时通知生产者生产商品
*/
public void consume() {
for (int i = ; i < ; i++) {
synchronized (stack) {
Systemoutprintln(consumer get the lock)
while (stacksize() == ) {
try {
stackwait()
} catch (InterruptedException e) {
// TODO Autogenerated catch block
eprintStackTrace()
}
}
// 模拟消费者消费商品所需的时间
try {
Threadsleep()
} catch (InterruptedException e) {
// TODO Autogenerated catch block
eprintStackTrace()
}
Object obj = stackpop()
Systemoutprintln(cosumer consume + obj)
}
}
}
public void run() {
consume()
}
}
public class Test{
public static void main(String[] args) {
Stack stack = new Stack()
Consumer consumer = new Consumer()
consumersetStack(stack)
Producer producer = new Producer()
producersetStack(stack)
Producer producer = new Producer()
producersetStack(stack)
consumerstart()producerstart()producerstart()
}
}