生产者消费者模式:不同种类的线程间针对同一个资源的操作
问题:
A:如果消费者先抢到cpu的执行权,就会去消费数据,但是现在的数据是默认值,没有意义,应该等着数据有意义,再消费
B:如果生产者先抢到cpu的执行权,就会去产生数据,但是,他产生完数据后,还继续拥有执行权,他继续产生数据。应该等着消费者把数据消费掉,然后再生产。
正常思路:
A: 生产者
先看是否有数据,有就等待,没有就生产,生产完之后通知消费者消费
B:消费者
先看是否有数据,有就消费,没有就等待,通知生产者生产数据
使用等待唤醒机制,wait(), notify(), notifyAll()方法来实现
这些方法是Object类的方法,方法的调用必须通过锁对象调用,锁对象可以是任意对象,所以等待唤醒机制的相关方法定义在Object类中。
代码实现如下:
public class Student {
private String name;
private int age;
private boolean flag;
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 GetThread implements Runnable{
private Student s;
public GetThread(Student s){
this.s = s;
}
@Override
public void run() {
while(true){
s.get();
}
}
}
public class SetThread implements Runnable{
private int x = 0;
private Student s;
public SetThread(Student s){
this.s = s;
}
@Override
public void run() {
while(true){
if(x % 2 == 0){
s.set("haha", 24);
}else{
s.set("lala", 26);
}
x++;
}
}
}
public class StudentDemo {
public static void main(String[] args) {
Student s = new Student();
GetThread gt = new GetThread(s);
SetThread st = new SetThread(s);
Thread t1 = new Thread(gt);
Thread t2 = new Thread(st);
t1.start();
t2.start();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)