资源类代码如下:
package com.dyn.itheima.test;
public class Student {
public boolean flag;
public String name;
public int age;
}
生产者类代码如下:
package com.dyn.itheima.test;
public class Producer implements Runnable {
// 资源对象
private Student student = null;
// 声明变量,用于下面判断赋值
private int index = 0;
public Producer(Student student) {
this.student = student;
}
@Override
public void run() {
while (true) {
synchronized (student) {
// 判断是否有产品,有的话,等待,没的话,生产
if (student.flag) {
try {
student.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
if (index % 2 == 0) {
student.name = "董以诺";
student.age = 22;
} else {
student.name = "胡歌";
student.age = 35;
}
index++;
// 改变产品标签,即设置有产品
student.flag = true;
// 唤醒消费者
student.notify();
}
}
}
}
}
消费者代码类如下:
package com.dyn.itheima.test;
public class Customer implements Runnable {
// 创建资源对象变量
private Student student;
public Customer(Student student) {
this.student = student;
}
@Override
public void run() {
while (true) {
synchronized (student) {
// 判断是否有产品,有的话,消费,没的话,等待
if (!student.flag) {
try {
student.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println(student.name + "-------" + student.age);
// 改变产品标签,即设置没有产品
student.flag = false;
// 唤醒生产者,生产产品
student.notify();
}
}
}
}
}
测试类代码如下:
package com.dyn.itheima.test;
public class Test {
public static void main(String[] args) {
//创建资源
Student student = new Student();
//创建生产者线程
Producer producer = new Producer(student);
//创建消费者线程
Customer customer = new Customer(student);
//调用生产者线程
new Thread(producer).start();
//调用消费者线程
new Thread(customer).start();
}
}
|