求一个生产者与消费者demo的内存关系图(百分相送)
代码如下:
class Info{
private String name=null; //名称
private String content=null; //内容
private boolean flag=false; //设置标志位
public synchronized void set(String name,String content){
if (!flag){
try{
super.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
try{
Thread.sleep(2000); //延迟
}catch(InterruptedException e){
e.printStackTrace();
}
this.setName(name); //设置名称
this.setContent(content); //设置内容
flag=false;
super.notify();
}
public synchronized void get( ){
if (flag){
try{
super.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
try{
Thread.sleep(2000); //延迟
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(this.getName()+"-->"+this.getContent());
flag=true;
super.notify();
}
public void setName(String name){ //设置名称
this.name=name;
}
public void setContent(String content){ //设置内容
this.content=content;
}
public String getName(){ //取得名称
return this.name;
}
public String getContent(){ //取得内容
return this.content;
}
}
class Producer implements Runnable{ //继承Runnable接口
private Info info=null; //声明info
public Producer(Info info){ //通过构造方法设置info
this.info=info;
}
public void run(){ //覆写run()方法
boolean flag=false; //声明flag
for (int i=0;i<50 ;i++ ){
if (flag){
this.info.set("徐彦","程序员");
flag=false;
}
else{
this.info.set("希哲","教师");
flag=true;
}
}
}
}
class Consumer implements Runnable{ //继承Runnable接口
private Info info=null; //声明info
public Consumer(Info info){
this.info=info;
}
public void run(){ //覆写run()
for (int i=0;i<50 ;i++ ){
this.info.get();
}
}
}
public class ThreadCaseDemo03{
public static void main(String args[]){
Info info=new Info(); //实例化info
Producer pro=new Producer(info); //生产者
Consumer con=new Consumer(info); //消费者
new Thread(pro).start();
new Thread(con).start();
}
}
小弟一直困惑程序的执行流程,希望通过内存图看个明白,各位大侠谢谢了啊!!!