复习之生产者——消费者问题

1.生产者消费者问题是实现线程同步的经典案例。


这里做一个对生产消费者问题做一个模拟:

我这里用一个  stack栈  用来存放产品,生产者生产产品,消费者消费产品,

class Stacks
{
	
	int index=0;
	matou []ms=new matou[6];

	public synchronized void push(matou m){
		
		if(index==ms.length){
			try{
				this.wait();
			}catch (Exception e){}
		}
		
	
	
	ms[index++]=m;
	this.notify();
	
	}
产品:

class matou
{
	private int id;
	public void setId(int id){

		this.id=id;
	}
	public int getId(){

		return id;
	}
	
	public matou(int id){

		this.id=id;
	}
}

生产者和消费者对栈的操作(开启器线程)

class Pro implements Runnable{

	private Stacks s;
	public Pro (Stacks s){
		this.s=s;
	}

	public void run(){
		for(int i=0;i<20;i++){
			matou m=new matou(i+1);
			s.push(m);
			System.out.print("生产了一个码头: matou"+m.getId());
			try{	Thread.sleep(1000);}catch (Exception e){}
			System.out.println();
			
		
	}
	
	}
}
class Cus implements Runnable{
	private Stacks s;
	public Cus (Stacks s){
		this.s=s;
	}
	public void run(){
	for(int i=0;i<20;i++){
		matou m=s.pop();
		
		try{	Thread.sleep(2000);}catch (Exception e){}
		System.out.println();
		System.out.println("消费了一个码头:matou"+m.getId());
		System.out.println();
	}	
	}

}
public class Pro_Cus{

	public static void main(String args[]){
		
		Stacks s=new Stacks();
		new Thread(new Cus(s)).start();
		new Thread(new Pro(s)).start();
	}
}
这里用到的synchornized关键字,用到了wait和signal机制,一个简单的模拟;

运行截图:设置的循环二十次,只是部分截图。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值