如何使用阻塞队列实现一个生产者和消费者模型

如何使用阻塞队列实现一个生产者和消费者模型?请写代码

使用基于数组的阻塞队列,有限次取水果和放水果

package com.tom.jdk5.concurrent.collections;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/*************************************
* 使用阻塞队列实现生产者消费者问题
*
* BlockingQueue的offer/poll操作不能满足阻塞等待的效果
*
*
*************************************/

class Plate {
// 一个盘子,可以放10个水果
private BlockingQueue fruits = new LinkedBlockingQueue(10);

// 如果有水果,则取得,否则取不走
///尝试取出元素,如果队列已空,则线程被阻塞
public String get() {
try {
return fruits.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
}
}
////尝试放入元素,如果队列已满,则线程被阻塞
public void put(String fruit) {
try {
fruits.put(fruit);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

生产者 

class Producer implements Runnable {

private Plate plate;

public Producer(Plate p) {
this.plate = p;
}

@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
//生产者准备生产的集合元素 /尝试放入元素,如果队列已满,则线程被阻塞
this.plate.put("" + i);
System.out.println("第" + i + "个水果放入盘子");
Thread.sleep((long) (200 * Math.random()));
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

消费者 

class Consumer implements Runnable {

private Plate plate;

public Consumer(Plate p) {
this.plate = p;
}

@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
String j = this.plate.get();
//消费者准备消费集合元素
System.out.println("第" + j + "个水果取出盘子");
Thread.sleep((long) (400 * Math.random()));
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
public class ProducerConsumerTest {
public static void main(String[] args) {
Plate p = new Plate();
Producer producer = new Producer(p);
Consumer consumer = new Consumer(p);
new Thread(producer).start();
new Thread(consumer).start();

}
}

 

你可能感兴趣的:(JAVA基础,并发)