黑马程序员技术交流社区

标题: 利用BlockingQueue解决生产者消费者问题为啥我的程序挂起啦? [打印本页]

作者: 晴天_SH    时间: 2014-4-24 21:42
标题: 利用BlockingQueue解决生产者消费者问题为啥我的程序挂起啦?
  1. public class ProduceConsumerDemo3 {
  2.     public static void main(String[] args) {
  3.             //创建一个容量为1的队列
  4.             BlockingQueue<String> bq=new ArrayBlockingQueue<String>(1);
  5.             //启动三个生产者
  6.             new Thread(new Producer1(bq)).start();
  7.             new Thread(new Producer1(bq)).start();
  8.             new Thread(new Producer1(bq)).start();
  9.            
  10.             //启动一个消费者
  11.             new Thread(new Consumer1(bq)).start();
  12.         }
  13. }
  14. class Producer1 implements Runnable
  15. {
  16.         private BlockingQueue<String> bq;
  17.         public Producer1(BlockingQueue<String> bq)
  18.         {
  19.                 this.bq=bq;
  20.         }
  21.         @Override
  22.         public void run() {
  23.                 String []strArr=new String[]{"java","struts","Spring"};
  24.                 for (int i = 0; i < 99999; i++)
  25.                 {
  26.                         System.out.println(Thread.currentThread().getName()+"----生产者----");
  27.                         try {
  28.                                 bq.put(strArr[i%3]);
  29.                         } catch (Exception e) {
  30.                                 // TODO: handle exception
  31.                         }
  32.                 }
  33.         }
  34. }
  35. class Consumer1 implements Runnable
  36. {
  37.         private BlockingQueue<String> bq;
  38.         public Consumer1(BlockingQueue<String> bd)
  39.         {
  40.                 this.bq=bq;
  41.         }
  42.         @Override
  43.         public void run() {
  44.                 while (true) {
  45.                        
  46.                         try {
  47.                                 System.out.println(Thread.currentThread().getName()+"---消费者--"+bq.take());
  48.                         } catch (Exception e) {
  49.                                 // TODO: handle exception
  50.                         }
  51.                
  52.                 }
  53.         }
复制代码

作者: 晴天_SH    时间: 2014-4-24 23:19
运行的时候,程序好像挂起啦,CPU一下子达到90%啦,谁能帮我分析下
作者: 晴天_SH    时间: 2014-4-24 23:27
不好意思,打扰各位啦,问题已经解决啦,我参数写错啦哎,太粗心啦,




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2