import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Created with IntelliJ IDEA.
* User: csx
* Date: 4/24/14
* Time: 9:56 AM
* To change this template use File | Settings | File Templates.
*
* 生產者與消費者模型中,要保證以下幾點:
* 1 同一時間內只能有一個生產者生產
* 2 同一時間內只能有一個消費者消費
* 3 生產者生產的同時消費者不能消費
* 4 消費者消費的同時生產者不能生產
* 5 共享空間空時消費者不能繼續消費
* 6 共享空間滿時生產者不能繼續生產
*
* 使用并發庫中的BlockingQueue(阻塞隊列) 實現生產者與消費者
*/
public class WaitNoticeDemo {
public static void main(String[] args) {
//固定容器大小為10
BlockingQueue foods = new LinkedBlockingQueue(10);
Thread produce = new Thread(new Produce(foods));
Thread consume = new Thread(new Consume(foods));
produce.start();
consume.start();
}
}
/**
* 生產者
*/
class Produce implements Runnable{
private BlockingQueue foods;
Produce(BlockingQueue foods) {
this.foods = foods;
}
@Override
public void run() {
int i = 0;
while (true){
try {
//當生產的食品數量裝滿了容器,那么在while里面該食品容器(阻塞隊列)會自動阻塞 ?wait狀態 等待消費
foods.put(new Food("食品"+i));
i++;
} catch (InterruptedException e) {
e.printStackTrace(); ?//To change body of catch statement use File | Settings | File Templates.
}
}
}
}
/**
* 消費者
*/
class Consume implements Runnable {
private BlockingQueue foods;
Consume(BlockingQueue foods){
this.foods = foods;
}
@Override
public void run() {
try {
Thread.sleep(1000); ?//用于測試當生產者生產滿10個食品后是否進入等待狀態
while (true){
//當容器里面的食品數量為空時,那么在while里面該食品容器(阻塞隊列)會自動阻塞 ?wait狀態 等待生產
Food food = foods.take();
System.out.println("消費"+food.getName());
}
} catch (InterruptedException e) {
e.printStackTrace(); ?//To change body of catch statement use File | Settings | File Templates.
}
}
}
/**
* 食品
*/
class Food{
private String name;
String getName() {
return name;
}
Food(String name){
this.name = name;
System.out.println("生產"+name);
}
}
如有不足 還請大家留言糾正修改。