`

生产者与消费者实例

阅读更多

 

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(); // 启动线程
 }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics