java多线程实现生产者/消费者同步

问题:主进程开两条线程,一条线程生产,一条线程消费。要求生产者不能过度生产,即生产的产品有数量上限,假定就是5个,消费者不能过度消费,即不能没有了产品也在消费 。

Buffer类,用作缓冲区

import java.util.*;

public class Buffer {
	private static final int BufferSize = 5;
	private Vector<Object> buffer = new Vector<Object>(BufferSize);
	private int objNum = 0;

	public synchronized void in(Object obj) {
		while (objNum == BufferSize) {
			try {
				this.wait();
			} catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
		buffer.add(obj);
		objNum++;
		if (objNum >= 1)
			this.notifyAll();
	}

	public synchronized Object out() {
		while (objNum == 0) {
			try {
				this.wait();
			} catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
		objNum--;
		Object o = buffer.remove(0);
		if(objNum <= 5)
			this.notifyAll();
		return o;
	}
}

生产者和消费者类:

public class Producer implements Runnable{
	private Buffer b = null;

	public Producer(Buffer b) {
		this.b = b;
	}

	public void run() {
		for(int i = 0; i < 199; i++) {
			synchronized(b) {
				Object o = new Object();
				b.in(o);
				System.out.println("Producer " + i);
			}
		}
	}
}

public class Consumer implements Runnable{
	private Buffer b = null;

	public Consumer(Buffer b) {
		this.b = b;
	}

	public void run() {
		for(int i = 0; i < 199; i++) {
			synchronized(b) {
				Object o = b.out();
				System.out.println("Consumer " + i);
			}
		}
	}
}

测试类:

public class TestDriver {
	public static void main(String[] args) {
		Buffer b = new Buffer();
		Runnable p = new Producer(b);
		Runnable c = new Consumer(b);
		Thread producer = new Thread(p);
		Thread consumer = new Thread(c);

		producer.start();
		consumer.start();
		
		try {
			producer.join();
			consumer.join();
		} catch(Exception e) {}
		System.out.println("Test over");
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值