生产者和消费者问题

Posted on 2009-03-27 22:14 风花雪月 阅读(189) 评论(0)  编辑 收藏 引用 所属分类: java

class Person
{
 String name = "风花雪月";
 String content = "作者";
    private boolean flag = true;
 //flag为true则可以设置值,false则可以取值
 public synchronized void set(String name ,String content)
 {
  if(!flag)
  {
   try
   {
    wait();
   }
   catch (Exception e)
   {
   }
  }
  this.name = name ;
  try
    {
     Thread.sleep(100);
    }
    catch (Exception e)
    {
    }
  this.content = content ;
  flag = false;
  notifyAll();
 }
 public synchronized String get()
 {
  if(flag)
  {
   try
   {
    wait();
   }
   catch (Exception e)
   {
   }
  }
  flag = true;
  notifyAll();
  return this.name+"-->"+this.content;
 }
}

class Product implements Runnable
{
 private Person person = null;
 public Product(Person person)
 {
  this.person = person ;
 }
 public void run()
 {
  for(int i= 0;i<100;i++)
  {
   if(i%2==0)
   {
    person.set("conish","英文名");
   }
   else
   {
   
       person.set("风花雪月","作者");
   }
  }
 }
}
class Customer implements Runnable
{
 private Person person = null;
 public Customer(Person person)
 {
  this.person = person ;
 }
 public void run()
 {
  for(int i= 0;i<100;i++)
  {
      System.out.println(person.get());
  }
 }
}
public class ThreadTest11
{
 public static void main(String [ ]argc)
 {
  Person person = new Person();
  Product product = new Product(person);
  Customer customer = new Customer(person);
  new Thread(product).start();
  new Thread(customer).start();
 }
}

只有注册用户登录后才能发表评论。

posts - 22, comments - 1, trackbacks - 0, articles - 8

Copyright © 风花雪月