1.正常的思路:
A:生产者
先看是否有数据,有就等待,没有就生产,生产完之后通知消费者来消费数据
B:消费者
先看是否有数据,有就消费,没有就等待,通知生产者来生产数据
现实中可能存在这样的情况:1)如果消费者先抢到CPU执行权,就会去消费数据,但是现在的数据是默认值,没有意义,应该等着数据有意义,再去消费。1)如果生产者先抢到CPU执行权,就会去生产数据,但是,它生产完数据之后,还继续拥有执行权,它继续产生数据,这就存在问题,应该等消费者把数据消费掉,再去生产。为了解决这样的问题,JAVA提供了一种机制,等待唤醒机制。下面为代码实现
生产者:
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("张三", 18);
} else {
s.set("李四", 20);
}
x++;
}
}
}
消费者:
public class GetThread implements Runnable{
private Student s;
public GetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
s.get();
}
}
}
public class Student {
private String name;
private int age;
private boolean flag; // 默认情况是没有数据,如果是true,说明有数据
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);
this.flag = false;
this.notify();
}
}
public class StudentDemo {
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);
t1.start();
t2.start();
}
}