package cn.project.demo;
/********
* 生产者和消费者案例
* 生产者和消费者交叉使用数据(1和2交替)
* 1.生产者和消费者同时使用数据时,生产者正在生产数据,而消费者正在等待中,当生产者生产完数据后,提醒生产者继续生产数据,并启动唤醒机制,消费者就开始取数据
* 2.当消费者正在取数据的过程中,此时生产者已经开始继续生产数据并在等待中,等消费者取完数据后,启动唤醒机制,于是生产者生产完数据,再次唤醒消费者去取数据
*******/
class Data{
private String tile;
private String note;
//flag=true 正在生产数据,不可以取走数据
//flag=false 生产完,可取走数据
private boolean flag=false;
/**
* 生产数据
* */
public synchronized void set(String tile,String note){
if(this.flag==true){
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.tile=tile;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.note=note;
this.flag=true;//继续生产数据
super.notify();
}
/**
* 取数据
* */
public synchronized void get(){
if(this.flag==false){
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.tile+"--"+this.note);
this.flag=false;//继续取数据
super.notify();
}
}
class DataProvider implements Runnable{
private Data data;
public DataProvider(Data data){
this.data=data;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
if(i%2==0){
this.data.set("tile1", "note1");
}else {
this.data.set("tile2", "note2");
}
}
}
}
class DataConsumer implements Runnable{
private Data data;
public DataConsumer(Data data){
this.data=data;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
this.data.get();
}
}
}
public class ThreadProviderAndConsumer {
public static void main(String[] args) {
Data data=new Data();
new Thread(new DataProvider(data)).start();
new Thread(new DataConsumer(data)).start();
}
}