2015-01-09 1505 views
0

我用信號量實現了生產者和消費者問題。 我需要一種方式,當沒有消費的產品時,當前線程將等到 生產者生產產品。 請指導我。如何停止java中信號量的特定thead?

+0

和當前的代碼是什麼?沒有代碼,沒有幫助... – fge 2015-01-09 21:05:52

回答

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(); 
    } 
}