关键:生产者不会在缓冲区满时加入数据,消费者不会在缓冲区空时消费数据
- 生产者持续生产,直到buffer满,满时阻塞;buffer不满后,继续生产
- 消费者持续消费,直到buffer空,空时阻塞;buffer不空后,继续消费
方法1: BlockingQueue实现
class Producer implements Runnable {
private BlockingQueue<Integer> queue;
private static AtomicInteger count = new AtomicInteger(0);
private static final int SLEEPTIME = 1000;
private volatile boolean isRunning = true;
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
int data;
Random random = new Random();
System.out.println("start producer id = " + Thread.currentThread().getId());
while (isRunning) {
try {
Thread.sleep(random.nextInt(SLEEPTIME));
data = count.incrementAndGet();
S