【发布时间】:2015-06-08 05:33:59
【问题描述】:
下面是我针对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在多生产者情况下容量有限? -
嗨,安迪,我知道在实际实施中类是更好的选择,但我正在准备面试,所以我想知道如何使用信号量来做到这一点。
标签: java multithreading operating-system semaphore producer-consumer