说我正在实现生产者-消费者模型。生产者和消费者共享缓冲区,这是关键区域。生产者要写入缓冲区,而消费者要从缓冲区读取。
为简单起见,此示例使用二进制信号量,其中一次只能有1个线程可以访问该缓冲区。信号量通常是生产者/消费者类的一部分还是应该属于缓冲区类?
// Producer class
class Producer implements Runnable {
Buffer buffer;
... more code
}
// Buffer class
class Buffer {
Deque<Integer> buffer;
private final Semaphore producerSemaphore;
private final Semaphore consumerSemaphore;
... more code
}
与
// Producer class
class Producer implements Runnable {
Buffer buffer;
private final Semaphore producerSemaphore;
... more code
}
// Buffer class
class Buffer {
Deque<Integer> buffer;
... more code
}