Java多线程:生产者与消费者

2014-11-23 21:36:50 · 作者: · 浏览: 56

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


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


  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();


  }