package blockque;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class SyncTest {
  public static void main(String args[]) {
    BlockingQueue<String> queue=new ArrayBlockingQueue<String>(100);
    Producer producer1 = new Producer(queue,"producer1");
    Consumer consumer1 = new Consumer(queue,"consumer1");
    Consumer consumer2 = new Consumer(queue,"consumer2");
  }
}

/**  生产者线程  */
class Producer extends Thread {
  private BlockingQueue<String> queue;

  public Producer (BlockingQueue<String> queue,String name) {
    super(name);
    this.queue = queue;
    start();  //启动自身生产者线程
  }

  public void run() {
    String goods;
    for (int i = 0; i < 200; i++) {
      try{
        goods="goods"+i;
        queue.put(goods);
        System.out.println(getName()+ ": put " + goods +" to the queue");
      }catch(Exception e){e.printStackTrace();}
    }
  }
}

/**  消费者线程 */
class Consumer extends Thread {
  private BlockingQueue<String> queue;

  public Consumer (BlockingQueue<String> queue,String name) {
    super(name);
    this.queue = queue;
    start();  //启动自身消费者线程
  }

  public void run() {
    String goods;
    for (int i=0; i < 200; i++) {
      try{
        goods = queue.take();
        yield();
        System.out.println(getName() + ": take " + goods +" from the queue");
     }catch(Exception e){e.printStackTrace();}
    }
  }
}



/****************************************************
 * 作者：孙卫琴                                     *
 * 来源：<<Java面向对象编程>>                       *
 * 技术支持网址：www.javathinker.net                *
 ***************************************************/

 


