Java生产者消费者模式同步的问题

本文通过具体代码示例,深入探讨了生产者消费者模式中线程同步机制的应用,特别是Java中wait和notify方法的使用。文章展示了一个简单的消息队列实现,其中生产者线程不断向队列中添加元素,而消费者线程则从队列中移除元素。
摘要由CSDN通过智能技术生成

学习下生产者消费者模式下,线程同步的问题。当然对这些问题,Java已经在concurrent包下已经做了处理,以下代码仅仅为了学习下多线程wait和notify。

import java.util.concurrent.ArrayBlockingQueue;

public class ProducerAndConsumer {
	public static void main(String[] args) {
		System.out.println("program start");
		MessageQueue<Object> queue = new MessageQueue<Object>(10000);
		Thread prodThread = new ProducerThread(queue);
		Thread consThread = new ConsumerThread(queue, prodThread);
		prodThread.start();
		consThread.start();
		if (consThread.isAlive() && prodThread.isAlive()) {
			System.out.println("all thread has started and running.");
		}
	}
}

class MessageQueue<T> extends ArrayBlockingQueue<T> {
	private int capacity;

	public MessageQueue(int capacity) {
		// TODO Auto-generated constructor stub
		super(capacity);
		this.capacity = capacity;
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = -8900156905307830983L;

	@Override
	public void put(T e) throws InterruptedException {
		// TODO Auto-generated method stub
		if (size() < capacity) {
			super.put(e);
			return;
		}

		synchronized (this) {
			if (size() > capacity) {
				wait();
				super.put(e);
				return;
			}
		}
		super.put(e);
	}

	@Override
	public T remove() {
		// TODO Auto-generated method stub
		if (size() < capacity && size() > 0) {
			return super.remove();
		}

		T t = null;
		while (size() > 0) {
			synchronized (this) {
				t = super.remove();
				notify();
			}
		}
		return t;
	}
}

class ConsumerThread extends Thread {
	MessageQueue<Object> queue;
	Thread producerThread;

	public ConsumerThread(MessageQueue<Object> queue, Thread producerThread) {
		// TODO Auto-generated constructor stub
		this.queue = queue;
		this.producerThread = producerThread;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (producerThread.isAlive()) {
			if (queue.size() > 0) {
				Object obj = queue.remove();
				System.out.println("consum: " + obj.toString() + " size: " + queue.size());
			}
		}
	}
}

class ProducerThread extends Thread {
	MessageQueue<Object> queue;

	public ProducerThread(MessageQueue<Object> queue) {
		// TODO Auto-generated constructor stub
		this.queue = queue;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void run() {
		// TODO Auto-generated method stub
		int i = 0;
		while (true) {
			try {
				queue.put(i++);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Thread.currentThread().stop();
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值