Student.java
package cn.itcast.productAndConsumer;
public class Student {
private String name;
private int age;
private 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 boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
SetThread.java
package cn.itcast.productAndConsumer;
public class SetThread implements Runnable {
private Student s;
private int x = 0;
public SetThread(Student s) {
super();
this.s = s;
}
@Override
public void run() {
while (true) {
synchronized (s) {
//判断生产者有没有生产好数据
if(s.isFlag()){
try {
s.wait(); // 线程执行wait方法,就会立即释放锁,将来醒过来的时候,就从这里醒来
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (x % 2 == 0) {
s.setName("林青霞");
s.setAge(27);
}else{
s.setName("王江");
s.setAge(18);
}
x++;
//生产者生产好了数据 ,打好标记并唤醒消费者的线程
s.setFlag(true);
s.notify();
}
}
}
}
GetThread.java
package cn.itcast.productAndConsumer;
public class GetThread implements Runnable {
private Student s;
public GetThread(Student s) {
super();
this.s = s;
}
@Override
public void run() {
while(true){
synchronized (s) {
if(!s.isFlag()){
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s.getName()+"---"+s.getAge());
//消费者消费完了数据,打标记并唤醒生产者线程
s.setFlag(false);
s.notify();
}
}
}
}
ProductAndConsumerDemo.java
package cn.itcast.productAndConsumer;
/***
* 等待唤醒:
* Object类中提供了三个方法:
* wait() 等待
* notify() 唤醒单个线程
* notifyAll() 唤醒所有线程
*
* 为什么这些方法不定义在Thread类中?
* 这些方法的调用必须通过锁对象调用,而我们刚才使用的锁对象是任意锁对象
* 所以这些方法必须定义在Object类中
*
*/
public class ProductAndConsumerDemo {
public static void main(String[] args) {
//创建资源
Student s = new Student();
//生产者和消费者
SetThread st1 = new SetThread(s);
GetThread st2 = new GetThread(s);
//线程类
Thread t1 = new Thread(st1);
Thread t2 = new Thread(st2);
t1.start();
t2.start();
}
}