生产者与消费者实例

本文介绍了一个使用Java实现的简单同步生产者-消费者模式案例。通过一个共享资源对象,生产者不断生产数据,而消费者从该对象中取出数据。利用synchronized关键字及wait/notify方法确保了线程间的正确同步。

 

public class Info {
 private String title = "张三";
 // private String title = "CHINA";
 private String content = "李四";
 // private String content = "US";
 private boolean flag = false; // 默认是false

 /*
  * 1、flag = true,表示可以生产,但是不能取走
  *
  * 2、flag = false,表示可以取走,但是不能生产
  */
 public synchronized void set(String title, String content) {
  if (flag == false) {// 已经生产过了,需要等待
   try {
    super.wait(); // 等待
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  this.setTitle(title);
  try {
   Thread.sleep(300); // 休眠0.3秒
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  this.setContent(content);
  this.flag = false;// 表示不能生产了
  super.notify(); // 唤醒其他等待的线程
 }

 public synchronized void get() {
  if (flag == true) {// 表示不能取
   try {
    super.wait(); // 等待
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  System.out.println(this.title + " --> " + this.content);
  this.flag = true;// 表示不能取走了
  super.notify(); // 唤醒
 }

 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public String getContent() {
  return content;
 }

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

}

 

二 创建建生产者

public class Producer implements Runnable {
 private Info info = null;

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

 public void run() {
  for (int x = 0; x < 100; x++) { // 不断的生产
   if (x % 2 == 0) {// 是奇数
    this.info.set("李四", "US");
   } else {
    this.info.set("张三", "CHINA");
   }
  }
 }
}

 

三 创建消费者

public class Consumer implements Runnable {
 private Info info = null;

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

 public void run() {
  for (int x = 0; x < 100; x++) {
   this.info.get();
  }
 }

}

 

四 测试类

public class TestInfo{
 public static void main(String[] args) {
  Info info = new Info();
  Producer pro = new Producer(info); // 实例化生产者对象
  Consumer con = new Consumer(info); // 实例化消费者对象
  new Thread(pro).start(); // 启动线程
  new Thread(con).start(); // 启动线程
 }

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值