您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
javase第三季学习笔记-生产者与消费者应用案例
发布时间:2017-08-10 16:03:47编辑:雪饮阅读()
生产者与消费者应用案例
多线程的开发中有一个最经典的操作案例,就是生产者-消费者,生产者不断生产产品,消费者不断取走产品。
例如:饭店里的有一个厨师和一个服务员,这个服务员必须等待厨师准备好膳食。当厨师准备好时,他会通知服务员,之后服务员上菜,然后返回继续等待。这是一个任务协作的示例,厨师代表生产者,而服务员代表消费者。
代码示例:
package com.vince.thread;
//生产者与消费者应用案例
public class ThreadDemo {
public static void main(String[] args) {
Food f=new Food();
Producter p=new Producter(f);
Consumer c=new Consumer(f);
new Thread(p).start();
new Thread(c).start();
}
}
//生产者:厨师
class Producter implements Runnable{
private Food food;
public Producter(Food food){
this.food=food;
}
public void run(){
for(int i=0;i<100;i++){
if(i%2==0){
//调用线程安全的方法
food.set("炒凉皮","炒凉皮-味美大补");
}
else{
food.set("葱爆腰花","葱爆腰花-氧气凝神");
}
}
}
}
//消费者
class Consumer implements Runnable{
private Food food;
public Consumer(Food food){
this.food=food;
}
public void run(){
for (int i = 0; i < 100; i++) {
food.get();
}
}
}
//产品:食物
class Food{
private String name;
private String content;
private boolean flag=true;//true表示可以生产,不可以消费
//线程安全的生成产品的方法(防止值与键的不对应)
public synchronized void set(String name,String content){
if(!flag){
//让当前线程进入等待池等待,没有指定时间则需要其它线程唤醒
//释放对象锁,让出cpu时间,监视器又名对象锁
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setName(name);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setContent(content);
flag=false;//表示可以消费,不可以生产
this.notify();//唤醒在该监视器上的一个线程,唤醒是随机的任意性的
}
//线程安全的消费产品方法(防止值与键的不对应)
public synchronized void get(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName()+":"+this.getContent());
flag=true;
this.notify();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Food(String name, String content) {
super();
this.name = name;
this.content = content;
}
public Food() {
super();
}
@Override
public String toString() {
return "Food [name=" + name + ", content=" + content + "]";
}
}
关键字词:javase,生产者与消费者应用案例