java 生产者与消费者问题实现

调用wait的时候让出了对象锁

import java.util.*;
public class ProducerConsumer{
	public static void main(String []args){
			SynStack ss= new SynStack();
			Producer p = new Producer(ss,"Producer");
			Consumer c = new Consumer(ss,"Consumer");
			Thread pt =  new Thread(p);
			Thread ct =  new Thread(c);
			pt.start();
			ct.start();
	}
}

/*
 *要生产的对象
*/
class Product{
	int id ;		//标示是哪个产品
	public Product(int id){
		this.id = id ;
	}

	public String toString(){
		return "product:"+id;
	}
}

///共享的缓冲区
class SynStack{
	Product products[] = new Product[4];		//设置改缓冲区的大小为4个Product
	int top = 0;								//记录此时缓冲区(栈)中的位置
	public synchronized void push(Product p){
			while(top == products.length){
				try{
					this.wait();				//如果缓冲区处于满状态则让生产操作处于wait,此时对象锁也被释放
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
			
			products[top] = p ;					//将生产的产品加入缓冲区
			top ++;
			this.notifyAll();					//如果不是满状态则唤醒当前所有处于等待状态的线程,因此消费者线程也被唤醒进行消费,如果不是多生产者与多消费者只//需要this.notify()即可
	}

	public synchronized Product pop(){
			//System.out.println(top);
			while(top == 0){
				//System.out.println(top+"*");
				try{
					this.wait();				//如果缓冲区处于空状态则让消费操作处于wait,此时对象锁也被释放	
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
			
			top --;
			this.notifyAll();
			return products[top];				//返回当前栈顶对象

	}


}
//生产者.是一个多线程类
class Producer  implements Runnable{
	String producerName;
	SynStack ss = null;

	/*public Producer(String name){
		this.producerName = name ;
	}*/
	
	Producer(SynStack ss,String name) {
		this.ss = ss;
		this.producerName = name;
	}

	public void run(){
		for(int i = 0 ;i<10;i++){
			Product p = new Product(i);
			ss.push(p);
			System.out.println("生产者:"+producerName+"生产了:"+p.toString());
			try{
				Thread.sleep((int)(Math.random() * 500));
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}

}

class Consumer implements Runnable{
	String consumerName;
	SynStack ss = null;
	/*Consumer(String name ){
		this.consumerName = name;
	}*/
	Consumer(SynStack ss,String name) {
		this.ss = ss;
		this.consumerName = name;
	}
	public void run(){
		for(int i = 0;i<10;i++){
			Product p = ss.pop();
			System.out.println("消费者:"+consumerName+"消费了:"+p.toString());
				try{
				Thread.sleep(0);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值