如何在java中停止信号量中的特定thead?

时间:2015-01-09 21:02:23

标签: java semaphore producer-consumer

我已经用信号量实现了生产者和消费者问题。 我需要一种方法,当没有消费产品时,当前线程等到 生产者生产产品。 请指导我。

1 个答案:

答案 0 :(得分:2)

查看Java's BlockingQueue,它已经支持此行为。

从上面链接的JavaDoc中获取的代码,例如:

class Producer implements Runnable {
    private final BlockingQueue queue;
    Producer(BlockingQueue q) { queue = q; }
    public void run() {
        try {
           while (true) { queue.put(produce()); }
        } catch (InterruptedException ex) { ... handle ...}
      }
    Object produce() { ... }
}

class Consumer implements Runnable {
  private final BlockingQueue queue;
  Consumer(BlockingQueue q) { queue = q; }
  public void run() {
    try {
      while (true) { consume(queue.take()); }
    } catch (InterruptedException ex) { ... handle ...}
  }
  void consume(Object x) { ... }
}

class Setup {
  void main() {
    BlockingQueue q = new SomeQueueImplementation();
    Producer p = new Producer(q);
    Consumer c1 = new Consumer(q);
    Consumer c2 = new Consumer(q);
    new Thread(p).start();
    new Thread(c1).start();
    new Thread(c2).start();
  }
}