生产者--消费者,二者共享数据(Student对象),这里,生产者是SetStudent, 消费者是GetStudent。生产者负责放物品到Student中,消费者使用wait( )等待生产者的通知。当得到通知后,消费者取出物品,并且用notify( )通知生产者,可以再放下一批物品。
(1)生产者仅仅在仓储未满时候生产,仓满则停止生产。
(2)消费者仅仅在仓储有产品时候才能消费,仓空则等待。
(3)当消费者发现仓储没产品可消费时候会通知生产者生产。
(4)生产者在生产出可消费产品时候,应该通知等待的消费者去消费
//学生实体类作为共享资源
class Student {
private String name;// 姓名
private int age;// 年龄
boolean flag;// 标记变量,判断当前学生对象是否已创建赋值好
//生产者的功能 ,为studnet对象赋值
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();//唤醒正在等待此对象的单个线程监控。如果有任何线程在这个对象上等待,其中一个线程被唤醒。选择是任意的
}
//消费者的功能,打印sutdent对象的内容
public synchronized void get() {
if (!this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name + ":::" + age);
this.flag = false;
this.notify();
}
}
// 模拟生产者线程类
class SetStudent implements Runnable {
// 共享资源s
private Student s;
private int x = 0;
public SetStudent(Student s) {
this.s = s;
}
public void run() {
while (true) {
if (x % 2 == 0) {
s.set("郭靖", 27);
} else {
s.set("黄蓉", 18);
}
x++;
}
}
}
// 模拟消费者线程类
class GetStudent implements Runnable {
// 共享资源s
private Student s;
public GetStudent(Student s) {
this.s = s;
}
public void run() {
while (true) {
s.get();
}
}
}
// 测试类
public class Demo3{
public static void main(String[] args) {
Student s = new Student();
SetStudent ss = new SetStudent(s);
GetStudent gs = new GetStudent(s);
Thread t1 = new Thread(ss, "生产者");
Thread t2 = new Thread(gs, "消费者");
t1.start();
t2.start();
}
}