多线程——生产者消费者

注: 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;
	}
}
执行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值