模拟生产者与消费者实例,生产者生产一个产品,消费者就消费一个产品 ,然后生产者再生产,消费者再消费

  ***********************核心方法类****************

  package test.com;

  class Queue

  // key

  {

  int value;

  boolean bFull = false;

  public synchronized void put(int i) {

  if (!bFull) {

  value = i;

  bFull = true;

  notify();// 必须用在synchronized

  }

  try {

  wait();// 必须捕获异常

  } catch (InterruptedException e) {

  // TODO Auto-generated catch block

  e.printStackTrace();

  }

  }

  public synchronized int get() {

  if (!bFull)

  try {

  wait();//进入

  } catch (InterruptedException e) {

  // TODO Auto-generated catch block

  e.printStackTrace();

  }

  bFull = false;

  notify();

  return value;

  }

  }

  package test.com;

  class Producter extends Thread

  {

  Queue q;

  Producter (Queue q)

  {

  this.q=q;

  }

  public void run()

  {

  System.out.println(“********producter****start*****”);

  for(int i=1;i《10;i++)

  {

  System.out.println(“producter :”+i);

  q.put(i);

  }

  System.out.println(“********producter*****end****”);

  }

  }

  **********************************************************************

  ****************************消费者类*********************************

  package test.com;

  class Consumer extends Thread

  {

  Queue q;

  Consumer(Queue q)

  {

  this.q=q;

  }

  public void run()

  {

  System.out.println(“********Consumer****start*****”);

  while(true)

  {

  System.out.println(“Consumer:”+q.get());

  System.out.println(“********Consumer****end*****”);

  }

  }

  }

  ************************************************************************

  *******************************主函数调用类**********************************

  package test.com;

  public class Test {

  public static void main(String[] args) {

  Queue q=new Queue();

  Producter p=new Producter(q);

  Consumer c=new Consumer(q);

  p.start();

  c.start();

  }}

  *****************************************************************

  OK,实现完毕

  wait方法——把线程放入wait set

  notify方法——从wait set拿出线程

  notifyAll方法——从wait set拿出所有线程

  wait、notify、notifyAll是Object类的方法