生产者消费者问题
方式一
采用synchronized锁以及wait notify方法实现
public class WaitAndNotify {
public static void main(String[] args) {
Person p = new Person();
new Thread(new Consumer("生产者一", p), "生产者一").start();
new Thread(new Consumer("生产者二", p), "生产者二").start();
new Thread(new Consumer("生产者三", p), "生产者三").start();
new Thread(new Product("消费者一", p), "消费者一").start();
new Thread(new Product("消费者二", p), "消费者二").start();
new Thread(new Product("消费者三", p), "消费者三").start();
}
}
class Person {
// product quantity
private static int productQuantity = 0;
// maximal stock
private static int max_Stock = 100;
// 锁
private Object obj = new Object();
// 生产活动
public void produce() throws Exception {
synchronized (obj) {
while (productQuantity >= max_Stock) {
System.out.println(Thread.currentThread().getName() + "仓库放不下了");
obj.wait();
}
productQuantity++;
System.out.println(Thread.currentThread().getName() + "仓库中有:"
+ productQuantity + "个产品");
obj.notifyAll();
}
}
public void consume() throws Exception {
synchronized (obj) {
while (productQuantity <= 0) {
System.out.println(Thread.currentThread().getName() + "数量不足");
obj.wait();
}
productQuantity--;
System.out.println(Thread.currentThread().getName() + "卖完之后,仓库中有:"
+ productQuantity + "个产品");
obj.notifyAll();
}
}
}
// 消费者
class Consumer implements Runnable {
private Person p;
private String name;
public Consumer(String name, Person p) {
super();
this.p = p;
this.name = name;
}
public void run() {
// TODO 自动生成的方法存根
try {
p.consume();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
// 生产者
class Product implements Runnable {
private Person p;
private String name;
public Product(String name, Person p) {
super();
this.p = p;
this.name = name;
}
@Override
public void run() {
try {
p.produce();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
方式二
package classDemo;
import java.io.IOException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class AwaitAndSignal
{
public static void main(String[] args) throws IOException
{
PersonLock person = new PersonLock();
new Thread(new ConsumerLock(person), "消费者一").start();
new Thread(new ConsumerLock(person), "消费者二").start();
new Thread(new ConsumerLock(person), "消费者三").start();
new Thread(new ProductLock(person), "生产者一").start();
new Thread(new ProductLock(person), "生产者一").start();
new Thread(new ProductLock(person), "生产者一").start();
}
}
class ProductLock implements Runnable
{
private PersonLock person;
public ProductLock(PersonLock person)
{
this.person = person;
}
@Override
public void run()
{
for (int i = 0; i < 10; i++)
{
person.produce();
}
}
}
class ConsumerLock implements Runnable
{
private PersonLock person;
public ConsumerLock(PersonLock person)
{
this.person = person;
}
@Override
public void run()
{
for (int i = 0; i < 10; i++)
{
person.consume();
}
}
}
class PersonLock
{
private int foodNum = 0;
//锁
private ReentrantLock lock = new ReentrantLock();
//监听器
private Condition condition = lock.newCondition();
private final int MAX_NUM = 5;
public void produce()
{
lock.lock();
try
{
while (foodNum == MAX_NUM)
{
System.out.println("box is full,size = " + foodNum);
//停锁
condition.await();
}
foodNum++;
System.out.println("produce success foodNum = " + foodNum);
//唤醒锁
condition.signalAll();
}
catch(InterruptedException e)
{
e.printStackTrace();
} finally
{
//释放锁
lock.unlock();
}
}
public void consume()
{
lock.lock();
try
{
while (foodNum == 0)
{
System.out.println("box is empty,size = " + foodNum);
condition.await();
}
foodNum--;
System.out.println("consume success foodNum = " + foodNum);
condition.signalAll();
}
catch(InterruptedException e)
{
e.printStackTrace();
} finally
{
lock.unlock();
}
}
}
方式三
采用BlockingQueue实现
BlockingQueue也是java.util.concurrent下的主要用来控制线程同步的工具。
BlockingQueue有四个具体的实现类,根据不同需求,选择不同的实现类
1、ArrayBlockingQueue:一个由数组支持的有界阻塞队列,规定大小的BlockingQueue,其构造函数必须带一个int参数来指明其大小.其所含的对象是以FIFO(先入先出)顺序排序的。
2、LinkedBlockingQueue:大小不定的BlockingQueue,若其构造函数带一个规定大小的参数,生成的BlockingQueue有大小限制,若不带大小参数,所生成的BlockingQueue的大小由Integer.MAX_VALUE来决定.其所含的对象是以FIFO(先入先出)顺序排序的。
3、PriorityBlockingQueue:类似于LinkedBlockQueue,但其所含对象的排序不是FIFO,而是依据对象的自然排序顺序或者是构造函数的Comparator决定的顺序。
4、SynchronousQueue:特殊的BlockingQueue,对其的操作必须是放和取交替完成的。LinkedBlockingQueue 可以指定容量,也可以不指定,不指定的话,默认最大是Integer.MAX_VALUE,其中主要用到put和take方法,put方法在队列满的时候会阻塞直到有队列成员被消费,take方法在队列空的时候会阻塞,直到有队列成员被放进来
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable {
BlockingQueue<String> queue;
public Producer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
String temp = "A Product, 生产线程:"
+ Thread.currentThread().getName();
System.out.println("I have made a product:"
+ Thread.currentThread().getName());
queue.put(temp);//如果队列是满的话,会阻塞当前线程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable{
BlockingQueue<String> queue;
public Consumer(BlockingQueue<String> queue){
this.queue = queue;
}
@Override
public void run() {
try {
String temp = queue.take();//如果队列为空,会阻塞当前线程
System.out.println(temp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Test3 {
public static void main(String[] args) {
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
// BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
//不设置的话,LinkedBlockingQueue默认大小为Integer.MAX_VALUE
// BlockingQueue<String> queue = new ArrayBlockingQueue<String>(2);
Consumer consumer = new Consumer(queue);
Producer producer = new Producer(queue);
for (int i = 0; i < 5; i++) {
new Thread(producer, "Producer" + (i + 1)).start();
new Thread(consumer, "Consumer" + (i + 1)).start();
}
}
}
//BlockingQueue接口,扩展了Queue接口
package java.util.concurrent;
import java.util.Collection;
import java.util.Queue;
public interface BlockingQueue<E> extends Queue<E> {
boolean add(E e);
boolean offer(E e);
void put(E e) throws InterruptedException;
boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException;
E take() throws InterruptedException;
E poll(long timeout, TimeUnit unit)
throws InterruptedException;
int remainingCapacity();
boolean remove(Object o);
public boolean contains(Object o);
int drainTo(Collection<? super E> c);
int drainTo(Collection<? super E> c, int maxElements);
}
//我们用到的take() 和put(E e)
//两个方法,在ArrayBlockingQueue中的实现
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
final E[] items = this.items;
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == items.length)
notFull.await();
} catch (InterruptedException ie) {
notFull.signal(); // propagate to non-interrupted thread
throw ie;
}
insert(e);
} finally {
lock.unlock();
}
}
private void insert(E x) {
items[putIndex] = x;
putIndex = inc(putIndex);
++count;
notEmpty.signal();
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == 0)
notEmpty.await();
} catch (InterruptedException ie) {
notEmpty.signal(); // propagate to non-interrupted thread
throw ie;
}
E x = extract();
return x;
} finally {
lock.unlock();
}
}
private E extract() {
final E[] items = this.items;
E x = items[takeIndex];
items[takeIndex] = null;
takeIndex = inc(takeIndex);
--count;
notFull.signal();
return x;
}
看得到其实也是利用了Lock以及Condition条件变量的await()方法和signal()方法实现的,这个实现和我们之前实现的Lock用法区别:
使用了两个条件变量 consume的await放置在notEmpty 之上,唤醒在put的时候,produce的await放置在notfull之上,唤醒在take()的时候,唤醒是signal而不是signalAll,这样做就不会因为大量唤醒导致竞争从而减低效率,通过锁对象的分析,减低竞争。
优点:更有利于协调生产消费线程的平衡。
package classDemo;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
/**
* ProducerConsumer是主类,Producer生产者,Consumer消费者,Product产品,Storage仓库
*/
public class ProducerConsumer {
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
Storage s = pc.new Storage();
ExecutorService service = Executors.newCachedThreadPool();
Producer p = pc.new Producer("张三", s);
Producer p2 = pc.new Producer("李四", s);
Consumer c = pc.new Consumer("王五", s);
Consumer c2 = pc.new Consumer("老刘", s);
Consumer c3 = pc.new Consumer("老林", s);
//执行线程
//提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future
service.submit(p);
//service.submit(p2);
service.submit(c);
service.submit(c2);
service.submit(c3);
}
//消费者
class Consumer implements Runnable {
private String name;
private Storage s = null;
public Consumer(String name, Storage s) {
this.name = name;
this.s = s;
}
public void run() {
try {
while (true) {
System.out.println(name + "准备消费产品.");
//取出产品消费
Product product = s.pop();
System.out.println(name + "已消费(" + product.toString() + ").");
System.out.println("===============");
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//生产者
class Producer implements Runnable {
private String name;
private Storage s = null;
public Producer(String name, Storage s) {
this.name = name;
this.s = s;
}
public void run() {
try {
while (true) {
//放入产品
Product product = new Product((int) (Math.random() * 10000)); // 产生0~9999随机整数
System.out.println(name + "准备生产(" + product.toString() + ").");
s.push(product);
System.out.println(name + "已生产(" + product.toString() + ").");
System.out.println("===============");
Thread.sleep(500);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
//仓库
public class Storage {
BlockingQueue<Product> queues = new LinkedBlockingQueue<Product>(10);
/**
* 生产
*
* @param p
* 产品
* @throws InterruptedException
*/
public void push(Product p) throws InterruptedException {
queues.put(p);
}
/**
* 消费
*
* @return 产品
* @throws InterruptedException
*/
public Product pop() throws InterruptedException {
return queues.take();
}
}
//产品
public class Product {
private int id;
public Product(int id) {
this.id = id;
}
public String toString() {// 重写toString方法
return "产品:" + this.id;
}
}
}
方式四:
public class Test5 {
final PipedInputStream pis = new PipedInputStream();
final PipedOutputStream pos = new PipedOutputStream();
{
try {
pis.connect(pos);
} catch (IOException e) {
e.printStackTrace();
}
}
class Producer implements Runnable {
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
int num = (int) (Math.random() * 255);
System.out.println(Thread.currentThread().getName()
+ "生产者生产了一个数字,该数字为: " + num);
pos.write(num);
pos.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pos.close();
pis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
int num = pis.read();
System.out.println("消费者消费了一个数字,该数字为:" + num);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pos.close();
pis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Test5 test5 = new Test5();
new Thread(test5.new Producer()).start();
new Thread(test5.new Consumer()).start();
}
}