package org.westos.生产者消费者模式;
/*
* 消费者与生产者模式:
* 消费者:输出数据
* 生产者:产生数据
* 这种模式中出了生产者消费者线程,我们还需要设置资源类,即包含数据的对象,还有测试类
* */
/**
* 这是一个测试类,它将会输出成片的资源类对象的信息,而不是像SetStudent代码那样相互交叉输出,这是因为没有等待唤醒机制
* 在加入Java等待唤醒机制后:
* 消费者:输出数据,当内存中有对象时,才会输出数据,否则处于等待中,向生产者发送信号,要求产生数据
* 生产者:产生数据,当内存中没有对象时,才会产生对象并设置数据,否则处于等待中,向消费者发送信号,要求输出数据
* 这就需要我们在Get/SetStudent线程中对资源类对象进行判断
* */
/**
* wait()与sleep()的区别
* wait()线程等待,停下当前线程去执行其他线程,会释放锁对象
* sleep()线程睡眠,理解为在线程中加入的一个延时函数,不会释放所对象
* */
public class Text {
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();
}
}
package org.westos.生产者消费者模式;
/**
* 这是一个资源类;
* 用于包含了学生的姓名,年龄数据
* */
public class Student {
private String name;
private int age;
//用于等待唤醒机制的判断
public boolean flag;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
package org.westos.生产者消费者模式;
/**
* 这是一个生产者,用于用于设置资源类对象的数据
* */
public class SetStudent implements Runnable {
//将生产者与资源类关联起来
private Student s;
public SetStudent(Student s) {
this.s =s;
}
private int i = 0;//一个用于判断的变量
@Override
public void run() {
while(true) {
synchronized (s) {
if(s.flag) {
try {
s.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(i%2==0) {
s.setName("张三");
s.setAge(12);
}else {
s.setName("李四");
s.setAge(13);
}
i++;
s.flag = true;
s.notify();
}
}
}
}
package org.westos.生产者消费者模式;
/**
* 这是一个消费者
* */
public class GetStudent implements Runnable{
private Student s;
public GetStudent(Student s) {
this.s = s;
}
@Override
public void run() {
while(true) {
synchronized (s) {
if(!s.flag) {
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s);
s.flag = false;
s.notify();
}
}
}
}