Java多线程—生产者-消费者问题

public class CubbyHole {
	private int seq;   //数据
	private boolean available=false;   //条件变量
	public synchronized int get()      //消费数据
	{
		while(available==false)        //无资源
		{
			try{
				wait();                //挂起
			}
			catch(InterruptedException e){
			}
		}
		available=false;
		notify();                       //唤醒
		return seq;
	}
	public synchronized void put(int value) //生产数据
	{
		while(available==true)             //已有资源
		{
			try{
				wait();                  //挂起
			}
			catch(InterruptedException e){
			}
		}
		seq=value;
		available=true; 
		notify();                        //唤醒
	}
}

public class Producer extends Thread{
	private CubbyHole cubbyhole;
	private int number;
	public Producer(CubbyHole c,int number)
	{
		cubbyhole=c;
		this.number=number;
	}
	public void run()
	{
		for(int i=0;i<10;i++)   //共生产10个
		{
			cubbyhole.put(i);
			System.out.println("Producer #"+this.number+" put: "+i);
			try{
				sleep((int)(Math.random()*100));
			}
			catch(InterruptedException e){}
		}
	}
}

public class Consumer extends Thread{
	private CubbyHole cubbyhole;
	private int number;
	public Consumer(CubbyHole c,int number)
	{
		cubbyhole=c;
		this.number=number;
	}
	public void run()
	{
		int value=0;
		for(int i=0;i<10;i++)   //不间断地连续消费10个
		{
			value=cubbyhole.get();
			System.out.println("Consumer #"+this.number+" got: "+value);
		}
	}
}

public class ProducerConsumeTest {

	public static void main(String[] args) {
		CubbyHole c=new CubbyHole();    //共享数据对象
		Producer p1=new Producer(c,1);
		Consumer c1=new Consumer(c,1);
		p1.start();
		c1.start();
	}
}

运行结果:

学习心得:

       生产者线程和消费者线程严格地轮流执行,获得了线程间的协调执行,达到了共享资源的互斥性操作;

       synchronized同步:保证了一个线程在一个完整操作的所有步骤的执行过程中,都独占相关资源而不被打断。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值