提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
之前学习生产者,消费者模型的时候遇到的一个特别形象的一个代码例子,记录一下
提示:以下是本篇文章正文内容,下面案例可供参考
一、代码示例
代码如下(示例):
package food;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class Foodmain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BlockingQueue<Food> queue = new LinkedBlockingQueue<Food>(10);
Producer[] p = new Producer[3];
Consumer[] c = new Consumer[15];
for (int i = 0; i < 3; i++) {
p[i] = new Producer(queue);
}
for (int j = 0; j < 15; j++) {
c[j] = new Consumer(queue);
}
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 3; i++) {
executorService.execute(p[i]);
}
for (int j = 0; j < 15; j++) {
executorService.execute(c[j]);
}
try {
Thread.sleep(1000 * 20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
消费者
package food;
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
private boolean working = true;
private BlockingQueue<Food> queue;
public Consumer(BlockingQueue<Food> queue) {
this.queue = queue;
}
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
//从阻塞队列中取出数据
Food food = queue.take();//take()方式,若队列中没有元素则线程被阻塞
System.out.println(food.getId() + "号食物已被"
+ Thread.currentThread().getId() + "号顾客端走");
Thread.sleep(1000 * 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
生产者
package food;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class Producer implements Runnable {
private BlockingQueue<Food> queue;
boolean working = true;
private static AtomicInteger count = new AtomicInteger();
public Producer(BlockingQueue<Food> queue ){
this.queue = queue;
}
public void run() {
// TODO Auto-generated method stub
while(working){
int id = count.incrementAndGet();
Food food = new Food(id);
System.out.println(Thread.currentThread().getId()+"号员工开始工作");
if(queue.offer(food)){
System.out.println(Thread.currentThread().getId()+"号员工将"+food.getId()+"号食物加入餐台");
}else{
System.out.println("餐台已满,"+food.getId()+"号食物无法加入");
}
try{
Thread.sleep(1000*3);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void stop(){
working=false;
}
}
食物类
package food;
public class Food {
private int id;
//含参构造函数,这里用不到无参构造器,所以可以不写。否则新建对象将会出错。
public Food(int id){
this.id=id;
}
//get/set
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}