多线程---生产者消费者模式
案例:
package com.mokuiran.thread.pcquestion;
public class PCTest{
public static void main(String[] args) {
//测试消费者生产者
ValueOP valueOP = new ValueOP();
ProductorThread p = new ProductorThread(valueOP);
ConmuserThread c = new ConmuserThread(valueOP);//从valueOP对象中读取数据
p.start();
c.start();
}
}
class ValueOP{
private String value = "";//定义一个空的字符串
//定义方法修改value字段的值(模拟生产者生产数据)
public void setValue(){
synchronized (this){
//如果value值不是空串("")就等待
while (!value.equalsIgnoreCase("")){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果value字段值是空串,就设置value字段的值
String value = System.currentTimeMillis()+"-"+System.nanoTime();
System.out.println("set设置的值是:"+value);
this.value = value;
// this.notify(); //在多生产者多消费者环境中,notify()不能保证是生产者唤醒消费者,如果生产者唤醒的还是生产者可能会出现假死的情况
this.notifyAll();
}
}
//定义方法读取字段(模拟消费者消费数据)
public void getValue(){
synchronized (this){
//如果value是空串就等待
while (value.equalsIgnoreCase("")){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//不是空串,就读字段值
System.out.println("get的值为:"+this.value);
this.value = "";//读完之后重新将value值赋空值
this.notifyAll();
}
}
}
class ProductorThread extends Thread{
//调用生产者(setValue()方法)
private ValueOP obj;
ProductorThread(ValueOP obj){
this.obj = obj;
}