实现生产者——消费者问题的第三种方式:使用java5提供的java.util.concurrent.BlockingQueue阻塞队列实现,你可以看到仓库类代码实现更加简洁了。同样,生产者类、消费者类都不变化(《java线程:三种方式实现生产者消费者问题_1》),以下是仓库类的代码实现:
- <span style="font-family:Arial;">
- /**
- * 仓库:
- * 先生产的先消费:采用JDK提供的阻塞队列实现生产者——消费者的问题
- */
- public class Storage {
- public static final int MAX_SIZE = 100;
- // 阻塞队列
- private BlockingQueue<Object> container = new ArrayBlockingQueue<Object>(MAX_SIZE);
- // 从仓库中存放一个产品:
- public void put(){
- try {
- sop("仓库现有数量为"+ container.size() +", 开始生产");
- /*
- * 关于put()、offer()、add():
- * put()
- * 如果队列中数据已满,则等待,该方法是阻塞的
- * offer()
- * 如果队列中数据已满,则返回插进队列的元素
- * add()
- * 如果队列中数据已满,则抛出异常
- */
- container.put(new Object());
- } catch (InterruptedException e) {
- }
- }
- // 从仓库中取出一个产品:
- public Object get(){
- Object obj = null;
- try {
- sop("仓库现有数量为"+ container.size() +", 开始消费");
- /*
- * 关于take()、poll()、remove():
- * take():
- * 如果队列没有数据,则一直等待队列的头部,直到头元素可用,该方法是阻塞的
- * poll():
- * 如果队列没有数据,则在指定的时间内等待队列的头部
- * remove():
- * 如果队列中没有元素,则抛出异常
- */
- obj = container.take();
- } catch (InterruptedException e) {
- }
- return obj;
- }
- private static void sop(Object obj){
- System.out.println(obj);
- }
- }
- </span>
以下是测试代码:
- <span style="font-family:Arial;">
- public class Test {
- public static void main(String[] args) {
- Storage storage = new Storage();
- Consumer con = new Consumer(storage);
- Producer pro = new Producer(storage);
- new Thread(pro).start();
- new Thread(pro).start();
- new Thread(pro).start();
- new Thread(pro).start();
- // new Thread(con).start();
- // new Thread(con).start();
- // new Thread(con).start();
- // new Thread(con).start();
- new Thread(con).start();
- }
- }
- </span>