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

       问题描述:生产者的主要作用是生成一定量的数据放到缓冲区中,然后重复此过程。与此同时,消费者也在缓冲区消耗这些数据。该问题的关键就是要保证生产者不会在缓冲区满时加入数据,消费者也不会在缓冲区中空时消耗数据。

Test.java

package com.oracle.test5;

public class Test {
	public static void main(String[] args) {
		BufferPool bp=new BufferPool(10);
		Productor p=new Productor(bp);
		Custmer c=new Custmer(bp);
		new Thread(p).start();
		new Thread(p).start();
		new Thread(c).start();
	}
}
BufferPool.java

package com.oracle.test5;

public class BufferPool {
	private int capacity;//最大容量
	private int count=0;//当前数量

	public BufferPool(int capacity) {
		super();
		this.capacity = capacity;
	}
	public int getCapacity() {
		return capacity;
	}
	public void setCapacity(int capacity) {
		this.capacity = capacity;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public synchronized void add(){
		while(count>=capacity){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		count++;
		System.out.println("生产一个后剩余:"+count);
		notify();
	}
	public synchronized void sub(){
		while(count==0){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		count--;
		System.out.println("消费一个后剩余:"+count);
		notify();
	}
}
Custmer.java

package com.oracle.test5;

public class Custmer implements Runnable{
	private BufferPool bufferpool;
	
	public Custmer(BufferPool bufferpool) {
		super();
		this.bufferpool = bufferpool;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			bufferpool.sub();
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
Productor.java

package com.oracle.test5;

public class Productor implements Runnable{
	private BufferPool bufferpool;
	
	public Productor(BufferPool bufferpool) {
		super();
		this.bufferpool = bufferpool;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			bufferpool.add();
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值