Productor and Customer problem

[code=java]

class Person
{
 
    private String name="llj";
    private String content="";
    private boolean flag=false;
    public synchronized void set(String name,String content)
    {
     //flag 标志用来是否可以设置,否则等待
     //如果是假,表示等待不能去设置
     if(flag)
     {   
      try {
    wait();
   } catch (Exception e) {
    // TODO: handle exception
   }
     }
     this.name=name;
     try {
   Thread.sleep(100);
  } catch (Exception e) {
   // TODO: handle exception
  }
     this.content=content;
     //设置完成后更改标志flag为true
     flag=true;
     notifyAll();
    }
    public synchronized String get()
    {
     if(flag==false)
     {
      try {
    wait();
   } catch (Exception e) {
    // TODO: handle exception
   }
     }
     flag=false;
     notifyAll();
     String str=this.name+"-->"+this.content;
     return str;
    }
}

class Pro implements Runnable
{
 private Person per=null;
 public Pro(Person per)
 {
  this.per=per;
 }
 public void run() {
  // TODO Auto-generated method stub
  for(int i=0;i<100;i++)
  {
   if(i%2==0)
   {
    per.set("MLDN", "网站");
    
   }
   else {
    per.set("LLJ","作者");
   }
  }
 }}
class Cus implements Runnable
{
 private Person per=null;
 public Cus(Person per)
 {
  this.per=per;
 }
 public void run() {
  // TODO Auto-generated method stub
  for (int i = 0; i < 100; i++) {
   
   System.out.println(per.get());
  }
  
 }
 
}
public class ThreadDemo6 {
 public static void main(String args[])
 {
  Person per=new Person();
  Pro p=new Pro(per);
  Cus c=new Cus(per);
  new Thread(p).start();
  new Thread(c).start();
 }
}

[/code]

posted @ 2010-10-14 16:13  hailiang2013  阅读(165)  评论(0编辑  收藏  举报