import java
import java
/**
*
* @author Jay Chang
*
*/
class Stack {
private List<Object> list = new LinkedList<Object>()
/**
* 出棧
*
* @return
*/
public Object pop() {
return list
}
/**
* 將元素壓入棧
*
* @param obj
*/
public void push(Object obj) {
list
}
public int size() {
return list
}
}
/**
*
* @author Jay Chang
*
*/
class Producer extends Thread {
private Stack stack;
public Stack getStack() {
return stack;
}
/**
*
* @param stack
*/
public void setStack(Stack stack) {
this
}
/**
* 生產者生產商品
*/
public void produce() {
for (int i =
// 同步stack
synchronized (stack) {
System
//這裡指定存放商品的商品棧的最大容量為
while (stack
try {
//將生產者線程持有stack對象的鎖釋放
stack
} catch (InterruptedException e) {
e
}
}
// 模擬生產者生產商品過程所需的時間
try {
Thread
} catch (InterruptedException e) {
e
}
String goods =
//將生產的商品放到存放商品的商品棧中
stack
System
//喚醒在stack對象等待池中的等待的所有線程
stack
}
}
}
public void run() {
produce()
}
}
class Consumer extends Thread {
private Stack stack;
public Stack getStack() {
return stack;
}
public void setStack(Stack stack) {
this
}
/**
*
* 消費者消費商品
*/
public void consume() {
for (int i =
synchronized (stack) {
System
while (stack
try {
stack
} catch (InterruptedException e) {
// TODO Auto
e
}
}
// 模擬消費者消費商品
try {
Thread
} catch (InterruptedException e) {
// TODO Auto
e
}
Object obj = stack
System
}
}
}
public void run() {
consume()
}
}
public class Test{
public static void main(String[] args) {
Stack stack = new Stack()
Consumer consumer = new Consumer()
consumer
Producer producer
producer
Producer producer
producer
consumer
}
}
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27529.html