使用JAVA中的信号量的生产者/消费者问题

时间:2019-10-23 00:15:45

标签: synchronization

我对使用信号量实现的生产者/消费者问题有疑问。根据解决方案,代码类似于:

class Q {
  int n;
static Semaphore semCon = new Semaphore(0);
static Semaphore semProd = new Semaphore(1);
  void get() {
    try {
semCon.acquire();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught"); }

System.out.println("Got: " + n);
semProd.release(); }
  void put(int n) {
    try {
semProd.acquire();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught"); }
this.n = n; System.out.println("Put: " + n); semCon.release();
} }
class Producer implements Runnable {
  Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
for(int i=0; i < 20; i++) q.put(i);
} }
class Consumer implements Runnable {
  Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
for(int i=0; i < 20; i++) q.get();
} }
class ProdCon {
  public static void main(String args[]) {
Q q = new Q(); new Consumer(q); new Producer(q);
} }

我的问题是: 1.获得semProd的生产者线程如何释放semCon? 2. semCon定义为零许可,使用者线程如何获取它?

0 个答案:

没有答案