以下是文章的主要核心点
- 文中采用Stream流的方式创建多个生产者和消费者
- 利用对象的wait()进行阻塞
- 利用synchronized 的原理
- 创建唯一的Monitor的LOCK对象
- 通过notifyAll()唤醒阻塞,此处不能用notify()
import java.util.stream.Stream;
public class ProduceConsumer {
private int i;
final private Object LOCK = new Object();
private volatile boolean isProduced = false;
public void produce() throws InterruptedException {
synchronized (LOCK) {
if (isProduced) {
LOCK.wait();
} else {
i++;
System.out.println(Thread.currentThread().getName()+" P-----> " + i);
isProduced = true;
LOCK.notifyAll();
}
}
}
public void consumer() throws InterruptedException {
synchronized (LOCK) {
if (isProduced) {
System.out.println(Thread.currentThread().getName()+" C-----> " + i);
isProduced = false;
LOCK.notifyAll();
} else {
LOCK.wait();
}
}
}
public static void main(String[] args) {
ProduceConsumer produceConsumer = new ProduceConsumer();
Stream.of("P1", "P2", "p3").forEach(name -> {
new Thread(() -> {
while (true) {
try {
produceConsumer.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},name).start();
});
Stream.of("C1", "C2", "C3").forEach(name -> {
new Thread(() -> {
while (true) {
try {
produceConsumer.consumer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},name).start();
});
}
}