package org.jaychang.coreJava.review;
import java.util.LinkedList;
import java.util.List;
/**
*
* @author Jay Chang
*
*/
class Stack {
private List list = new LinkedList();
/**
* 出栈
*
* @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();
}
}
/**
*
* @author Jay Chang
*
*/
class Producer extends Thread {
private Stack stack;
public Stack getStack() {
return stack;
}
/**
*
* @param stack
*/
public void setStack(Stack stack) {
this.stack = stack;
}
/**
* 生产者生产商品,当商品栈满时,通知消费者消费商品
*/
public void produce() {
for (int i = 0; i < 100; i++) {
// 同步stack
synchronized (stack) {
System.out.println("producer get the lock");
//这里指定存放商品的商品栈的最大容量为10
while (stack.size() == 10) {
try {
//将生产者线程持有stack对象的锁释放,并将生产者线程放到stack对象的等待池中
stack.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}