2
下面是我實現的PC問題生產者消費者界緩衝區使用旗語
public class CircularQueue {
Queue <Integer>queue = new LinkedList<Integer>();
final int LIMIT = 10;
static Semaphore semProd = new Semaphore(1);
static Semaphore semConsu = new Semaphore(0);
public void enqueue(int productId) throws InterruptedException{
semProd.acquire();
queue.add(productId);
System.out.println(Thread.currentThread().getName()+" Putting(In Q) Product ID:"+productId);
semConsu.release();
}
public int deueue() throws InterruptedException{
semConsu.acquire();
int productID = (int) queue.remove();
System.out.println(Thread.currentThread().getName()+" Getting (In Q) Product ID:"+productID);
semProd.release();
return productID;
}
}
//producer class
public class Producer implements Runnable{
CircularQueue cQueue ;
public Producer(CircularQueue queue){
this.cQueue = queue;
}
public void run(){
while(true){
for(int i =0 ; i < 5 ;i++){
try {
cQueue.enqueue(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}}}
//consumer class
public class Consumer implements Runnable{
CircularQueue cQueue ;
public Consumer(CircularQueue cQueue){
this.cQueue = cQueue;
}
public void run(){
try {
while(true){
int item = cQueue.deueue();
Thread.sleep(2000);}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
//Driver Class
public class DriverClass {
public static void main(String args[]){
CircularQueue cQueue = new CircularQueue();
new Thread(new Producer(cQueue)).start();
new Thread(new Consumer(cQueue)).start();
}}
1)如何檢查我的實現是正確 2)如果我想編輯多個消費者和多個生產商的解決方案那麼我應該如何改變執行方式
正在增加semProduce的數量和sem消耗不夠?
static Semaphore semProd = new Semaphore(4);//4 producer
static Semaphore semConsu = new Semaphore(3);//3 consumer
爲什麼不使用來自'java.util.concurrent'的類,比如''SynchronousQueue'用於單個生產者情況,''BlockingQueue'在多生產者情況下容量有限? – 2015-04-03 06:25:45
嗨安迪我知道類是實際實施中更好的選擇,但我正在準備面試,所以我想知道如何用信號量做到這一點。 – user2895589 2015-04-03 15:54:18