Java并发——生产者-消费者


//生产者-消费者模型
//多线程的典型例子
public class ProducerConsumer {

	public static void main(String[] args)
	{
		Shared s = new Shared();
		new Producer(s).start();
		new Consumer(s).start();
	}
}

class Shared
{
	private char c;
	private volatile boolean writeable = true;
	
	synchronized void setSharedChar(char c)
	{
		while(!writeable)
		{
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		this.c = c;
		writeable = false;  //写完之后写标志置为false
		notify();           //写完之后将通知读操作
	}
	
	synchronized char getSharedChar()
	{
		while(writeable)
		{
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		writeable = true;
		notify();
		return c;
	}
}

//通过继承的方式创建线程
class Producer extends Thread
{
	private final Shared s;  //通过final关键字保证数据的原子性
	
	Producer(Shared s)
	{
		this.s = s;
	}
	
	@Override
	public void run()
	{
		for(char ch = 'A'; ch <= 'Z'; ch++)
		{
             synchronized(s)  //保证setSharedChar()方法后伴随的System.out.println()同步
             {
     			s.setSharedChar(ch);
    			System.out.println(ch + " produced by producer");
             }
		}
	}
}

class Consumer extends Thread
{
	private final Shared s;  //通过final关键字保证数据的原子性
	
	Consumer(Shared s)
	{
		this.s = s;
	}
	
	@Override
	public void run()
	{
		char ch;
		do
		{
			synchronized(s)  //保证getSharedChar()方法后伴随的System.out.println()同步
			{
				ch = s.getSharedChar();
				System.out.println(ch + " consumed by consumer.");
			}
		}
		while(ch != 'Z');
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值