线程同步:生产者和消费者问题

1、实现一个生产者

       

public class Producer implements Runnable {

	SyncStack stack;	//数据存放位置,和生产者是相同的位置

	public Producer(SyncStack s){
		stack = s;
	}
	public void run(){
		for(int i=0; i<20; i++){
			char c =(char)(Math.random()*26+'A');
			stack.push(c);//产品生产后,存放产品
			System.out.println("produced:"+c);
			try{							        
				Thread.sleep((int)(Math.random()*1000)); 
			}catch(InterruptedException e){
			}
		}
	}
}

 

2、实现消费者

   

public class Consumer implements Runnable {
	SyncStack stack;	//数据存放位置,和生产者是相同的位置
	public Consumer(SyncStack s){
		stack = s;
	}
	public void run(){
		for(int i=0;i<60;i++){
			char c = stack.pop();//往外拿产品,进行产品消费
			System.out.println("消费:"+c);
			try{							           
				Thread.sleep((int)(Math.random()*1000));
			}catch(InterruptedException e){
			}
		}
	}

}

 3、实现存放位置的线程同步

 

public class SyncStack {
	private int index = 0;
	private char []data = new char[6];	
	public synchronized void push(char c){
		while(index == data.length){
		try{
				this.wait();
				//某线程执行到这里时,篮子已经满了,那么就等待消费者消费。此时锁已经不再属于该线程
				
		}catch(InterruptedException e){}
		}
		this.notifyAll();//唤醒其他线程(消费者线程或者其他生产者线程)
		                     //主要是为了让消费者消费,才能唤醒其他等待的生产者线程
		                 
		data[index] = c;
		index++;
	}
	public synchronized char pop(){
		while(index ==0){
			try{
				this.wait();
				//某线程执行到这里时,篮子已经空了,那么就等待生产者生产,此时锁已经不属于该线程
				
			}catch(InterruptedException e){}
		}
		this.notifyAll();//唤醒其他线程(生产者线程或者其他消费这线程)
		                 //主要是为了让生产者生产,才能唤醒其它等待的消费者线程
		index--;           
		return data[index];
	}
}

 

5、测试类

    

public class ProducerConsumer {
	 public static void main(String args[]){
		  SyncStack stack = new SyncStack();//共享存储空间
		 Producer p=new Producer(stack);
		  Consumer c = new Consumer(stack);
	                  new Thread(p).start();//生产者线程
		 new Thread(p).start();//生产者线程
		 new Thread(p).start();//生产者线程
		 new Thread(c).start();//消费者线程
 }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值