生产者与消费者模型

/*Object类对线程的支持:
  唤醒有两个操作:notify()、notifyAll()。一般来说,所有等待的线程会按照顺序进行排列
  如果使用notify()则会唤醒第一个等待的线程执行,如果使用notifyAll()方法,则会唤醒所有的
  线程,那个线程的优先级高,那个线程就先执行


实现:
  如果要想让生产者生产一个就取走一个,则可以增加一个boolean型标志位,
  标志位是true:表示可以生产,但不能取走,如果此时线程执行到消费者,线程应该等待
  标志位是false:表示可以取走,但不能生产,如果此时线程执行到生产者,线程应该等待
*/
class Info{
private String name="Lee";  //定义name属性
private String content="JAVA学生"; //定义content属性
private boolean flag=false; //设置标志位

//设置同步取得方法
public synchronized void set(String name,String content){
if(!flag){   
try{
super.wait(); //等待
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.setName(name); //设置姓名
try{
Thread.sleep(90);  //加入延迟
 }catch(InterruptedException e){  //捕获异常
  e.printStackTrace();
 }
 this.setContent(content);  //设置内容
 flag=false;  //改变标志位,表示可以取走
 super.notify();
}

//设置同步取得方法
  public synchronized void get(){
  if(flag){
try{
super.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
try{
Thread.sleep(90);  //加入延迟
}catch(InterruptedException e){ //捕获异常 
e.printStackTrace();
}
 System.out.println(this.getName()+"-->"+this.getContent());
 flag=true;  //改变标志位,表示可以生产
 super.notify();
  }


  public void setName(String name){
this.name=name;
}
  public void setContent(String content){
this.content=content;
}

  public String getName(){
return this.name;
}
  public String getContent(){
return this.content;
}

}
//建立生产者类,生产者类实现多线程机制
class Producer implements Runnable{   //实现Producer接口
private Info info=null;    //保存Info引用

public Producer(Info info){
this.info=info;
}

public void run(){  //覆写run方法
boolean flag=false;  //定义标记位
for(int i=0;i<50;i++){
if(flag){
this.info.set("Lee","JAVA学生");
flag=false;
}else{
this.info.set("优快云","www.youkuaiyun.com");
flag=true;
}
}
}
};


//实现消费者类,消费者不断的取走信息
class Consumer implements Runnable{   //实现Consumer接口
private Info info=null;   //保存Info引用

public Consumer(Info info){   //构造方法
this.info=info;
}

public void run(){  //覆写run方法
for(int i=0;i<50;i++){
this.info.get();
}
}
};


public class ThreadCaseDemo03{
public static void main(String args[]){
Info info=new Info();  //实例化Info对象
Producer pro=new Producer(info);  //实例化Producer对象
Consumer con=new Consumer(info);  //实例化Consumer对象

new Thread(pro).start();  //启动pro线程
new Thread(con).start();  //启动con线程
}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值