二、生产者消费者模式的学生类成员变量生产与消费demo,

@Version2.0

  在学生类中添加同步方法:synchronized get()消费者,synchronized set()生产者

  最终版的代码中: 把student的成员变量给私有化了,
  把设置和获取的功能给封装成了功能,并加了同步,
  设置或者获取的线程里面只需要调用方法即可。

1、等待唤醒:
      Object类中提供了三个方法:
      wait():等待
      notify():唤醒单个线程
      notifyAll():唤醒所有线程
//==========================

//首先是重点学生类对象

 public class Student {
private String name;
private int age;
private boolean flag; // 同步方法
public synchronized void set(String name, int age) {
// 如果有数据就等待
if (this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} // 设置数据
this.name = name;
this.age = age; // 一旦有了数据修改标记,并唤醒
this.flag = true;
this.notify();
} // 同步获取方法
public synchronized void get() {
// 如果没有数据就等待
if (!this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 获取数据
System.out.println(this.name + "--- " + this.age);
//获取到数据后,修改标记为false,最后唤醒。
this.flag = false;
this.notify();
}

// 生产者的线程,这次超级简单~~~··

 public class setThread implements Runnable {
private Student s;
private int x = 0; public setThread(Student s) {
this.s = s;
} @Override
public void run() {
while (true) { if (x % 2 == 0) {
s.set("java", 30);
} else {
s.set("Android", 20);
}
x++;
} } }

// 消费者的线程,这次超级简单~~~··

 public class getThread implements Runnable {
private Student s; public getThread(Student s) {
this.s = s;
} public void run() {
while (true) {
s.get();
}
}
}

// 消费者的线程,这次超级简单~~~··

 public class Demo {
public static void main(String[] args) {
//共享数据,外界创建,作为参数,通过构造共有
Student s = new Student();
//在构造中使用同一个参数
setThread st = new setThread(s);
getThread gt = new getThread(s); Thread t1 = new Thread(st);// 设置数据
Thread t2 = new Thread(gt); // 获取数据 t2.start();
t1.start();
}
}

最新文章

  1. thinkphp怎么修改配置进入默认首页
  2. 执行打的maven jar包时出现“Exception in thread "main" java.lang.SecurityException: Invalid signature file digest for Manifest main attributes”
  3. UVALive6900 Road Repair(树的点分治)
  4. [转]Web3.0时代,企业知识管理新趋势
  5. android js调试
  6. mac下Android开发环境搭建
  7. For and While loop choice.
  8. 商人过河问题(二)java实现
  9. XP下採用DirectShow採集摄像头
  10. S2SH整合
  11. idea 端口占用
  12. 多线程编程学习笔记——使用异步IO(一)
  13. [HNOI2016]序列
  14. dp Surf
  15. CSS学习——基础分类整理
  16. 强化学习-Q-Learning算法
  17. gcd最大生成树模板
  18. HDU 1051 Wooden Sticks 造木棍【贪心】
  19. MFC工程说明readme
  20. [Java学习] 再谈Java包

热门文章

  1. jquery对于table的操作
  2. javascript学习笔记之DOM与表单
  3. Azure Remote Desktop: "An error occurred while loading from file *.rdp"
  4. jquery文字溢出处理,超出变省略号
  5. C# 集合-并发处理-锁OR线程
  6. MVC Router学习
  7. system(linux) power on note
  8. 、JAVA-异常
  9. Winform ListView 元素拖动
  10. [转] java书籍(给Java程序猿们推荐一些值得一看的好书 + 7本免费的Java电子书和教程 )