生产者消费者模式实现

生产者消费者模式实现(synchronized、wait和notify方式)

一. 基本流程
生产者在缓冲区未满时生产数据,消费者在缓冲区有数据时从缓冲区中取数据。
如果缓冲区已经满了,则生产者线程阻塞;
如果缓冲区为空,那么消费者线程阻塞。

二. 对象类型

  1. 生产者
  2. 消费者
  3. 仓库
  4. 产品

三. 代码实现

  1. 产品
package xyz.yyaosen.produce;

import java.util.ArrayList;
import java.util.List;

public class Produce {
	// 缓冲区-产品
	private static List<Integer> produce = new ArrayList<Integer>();
	// 缓冲区-容量
	private static final int VOLUME = 10;
	// 状态锁
	private Object lock;

	public Produce() {
	}

	public Produce(Object lock) {
		// TODO Auto-generated constructor stub
		this.lock = lock;
	}

	// 生产
	public void add() {
		synchronized (lock) {
			if (produce.size() < VOLUME) {
				produce.add(1);
				System.out.println("生产者" + Thread.currentThread().getId() + ",产品数量(+1):" + produce.size());
				lock.notifyAll();
			} else {
				try {
					System.out
							.println("生产者" + Thread.currentThread().getId() + ",产品数量(/):" + produce.size() + "/等待...");
					lock.wait(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	// 消费
	public void remove() {

		synchronized (lock) {
			if (produce.size() > 0) {
				produce.remove(produce.size() - 1);
				System.out.println("消费者" + Thread.currentThread().getId() + ",产品数量(-1):" + produce.size());
				lock.notifyAll();
			} else {
				try {
					System.out
							.println("消费者" + Thread.currentThread().getId() + ",产品数量(/):" + produce.size() + "/等待...");
					lock.wait(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}
}

  1. 消费者线程
package xyz.yyaosen.produce;

public class ConsumerThread implements Runnable {
	// 产品实例
	Produce produce = new Produce(new Object());

	// run
	public void run() {
		while (true) {
			produce.remove();
		}
	}
}
  1. 生产者线程
package xyz.yyaosen.produce;

public class ProduceThread implements Runnable {
	// 产品实例
	Produce produce = new Produce(new Object());

	// run
	public void run() {
		while (true) {
			produce.add();
		}
	}
}
  1. 入口类
package xyz.yyaosen.produce;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 消费者线程
		ConsumerThread consumerThread = new ConsumerThread();
		Thread cThread1 = new Thread(consumerThread);
		Thread cThread2 = new Thread(consumerThread);

		// 生产者线程
		ProduceThread produceThread = new ProduceThread();
		Thread pThread1 = new Thread(produceThread);
		Thread pThread2 = new Thread(produceThread);

		cThread1.start();
		cThread2.start();
		pThread1.start();
		pThread2.start();
	}
}

5.执行结果
生产者消费者模式实现

上一篇:python yield 和 yield from用法总结


下一篇:死亡之ping