阻塞队列和生产者-消费者模式

 自Java5以来提供的 BlockingQueue是一种特殊的队列, 它 是支持两个附加操作的 Queue,这两个操作是:检索元素时等待队列变为非空,以及存储元素时等待空间变得可用。

以JDK中的例子略加改写如下

1 import java.util.concurrent.ArrayBlockingQueue;
2 import java.util.concurrent.BlockingQueue;
3
4 class Producer implements Runnable {
5      private final BlockingQueue queue;
6
7      Producer(BlockingQueue q) {
8          queue = q;
9      }
10
11      public void run() {
12          try {
13              while ( true ) {
14                  queue.put(produce());
15              }
16          } catch (InterruptedException ex) {
17              System.out.println( " produce interrupted " + ex.getMessage());
18              Thread.currentThread().interrupt();
19              // return;
20          }
21      }
22
23      Object produce() {
24          System.out.println( " produce laugh " );
25          return " haha " ;
26      }
27 }
28
29 class Consumer implements Runnable {
30      private final BlockingQueue queue;
31
32      Consumer(BlockingQueue q) {
33          queue = q;
34      }
35
36      public void run() {
37          try {
38              while ( true ) {
39                  consume(queue.take());
40              }
41          } catch (InterruptedException ex) {
42              System.out.println( " consume interrupted " + ex.getMessage());
43              Thread.currentThread().interrupt();
44          }
45      }
46
47      void consume(Object x) {
48          System.out.println( " consume laugh " + x);
49      }
50 }
51
52 public class BlockingQueueTest {
53      public static void main(String args[]) {
54          BlockingQueue q = new ArrayBlockingQueue( 10 );
55          Producer p = new Producer(q);
56          Consumer c1 = new Consumer(q);
57          Consumer c2 = new Consumer(q);
58          Thread pTh = new Thread(p);
59          pTh.start();
60          Thread cTh1 = new Thread(c1);
61          cTh1.start();
62          Thread cTh2 = new Thread(c2);
63          cTh2.start();
64          try {
65              Thread.sleep( 3000 );
66          } catch (Exception e) {
67              // TODO: handle exception
68          }
69          pTh.interrupt();
70          cTh1.interrupt();
71          cTh2.interrupt();
72      }
73 }
74

posted on 2008-07-26 23:42

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值