注: Product为生产者(生产完16个馒头就结束),Customer为消费者(吃完16个馒头就结束),Mantou为生产的馒头,Stack为装馒头的篮框(是栈的类型,最多只能放6个馒头)。
import java.util.*;
public class ProductCustomer{
private static Stack s = new Stack();
public static void main(String[] args){
Product p = new Product(s);
Customer c = new Customer(s);
p.start();
c.start();
}
}
class Product extends Thread{
private Stack s;
public Product(Stack s){
this.s = s;
}
public void run() {
for(int i = 1; i <= 16; i++){
Mantou mt = new Mantou(i);
int flag = s.push(mt);
try{
Thread.sleep(100);
}catch(InterruptedException e){}
if(flag == 0){
i--;
}
}
}
}
class Customer extends Thread{
private Stack s;
public Customer(Stack s){
this.s = s;
}
public void run(){
for(int i = 1; i <= 16; i++){
int flag = s.pop();
try{
Thread.sleep(200);
}catch(InterruptedException e){}
if(flag == 0){
i--;
}
}
}
}
class Mantou{
int id;
public Mantou(int id){
this.id = id;
}
public int getId(){
return id;
}
}
class Stack{
private int index = 0;
private List<Mantou> mts = new ArrayList<Mantou>();
public synchronized int push(Mantou mt){
if(index == 6){
System.out.println("篮筐已满,稍候再放");
return 0;
}else{
mts.add(mt);
index++;
System.out.println("馒头" + mt.getId() + "放入篮筐" + index + "的位置");
return 1;
}
}
public synchronized int pop(){
Mantou mt = null;
if(index == 0){
System.out.println("篮筐已空,稍候再拿");
return 0;
}else{
mt = mts.get(index-1);
mts.remove(index-1);
System.out.println("馒头" + mt.getId() + "从篮筐" + index + "的位置取出");
index--;
return 1;
}
}
public int getIndex(){
return index;
}
public List<Mantou> getMts(){
return mts;
}
}
执行结果: