用信号量解决生产者消费者问题
来源:百度知道 编辑:UC知道 时间:2024/06/16 13:54:25
import java.util.concurrent.Semaphore;
class Q { //仓库
int n; //仓库中的产品
// Start with consumer semaphore unavailable.
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) {