高效的生产者消费者模型写法:生产者生产完产品,开始sleep时,释放锁
import lombok.extern.slf4j.Slf4j;
import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Slf4j
public class Demo {
public static void main(String[] args) {
final LinkedList<Integer> list = new LinkedList<>();
final Object monitor = new Object();
final Random random = new Random();
Runnable producerRunnable = new Runnable() {
@Override
public void run() {
while (true) {
synchronized (monitor) {
while (!list.isEmpty()) {
try {
monitor.wait();
} catch (InterruptedException e) {
log.error("e:{}", e);
}
}
}
{
log.info("producer start produce");
// 从上面的while出来,说明现在list空了,开始生产;假设耗时,在3s以内
try {
TimeUnit.SECONDS.sleep(random.nextInt(3));
} catch (InterruptedException e) {
}
int product = random.nextInt(1000);
list.add(product);
log.info("producer produce {}",product);
}
//因为生产比较耗时,所以我们这里前面把锁释放了,这里要通知消费者,需要再拿锁
synchronized (monitor) {
monitor.notify();
}
//
// //1 生产后,休息10s
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
}
}
}
};
Thread thread = new Thread(producerRunnable);
thread.setName("producer");
thread.start();
Runnable consumerRunnable = new Runnable() {
@Override
public void run() {
while (true) {
synchronized (monitor) {
while (list.isEmpty()) {
try {
monitor.wait();
} catch (InterruptedException e) {
log.error("e:{}", e);
}
}
}
// 从上面的while出来,说明现在list空了,开始生产;假设耗时,在3s以内
try {
int product = list.get(0);
log.info("consumer start consume {}", product);
int timeout = random.nextInt(3);
TimeUnit.SECONDS.sleep(timeout);
list.clear();
log.info("consumer consume {},spent {}", product, timeout);
} catch (InterruptedException e) {
}
//因为消费比较耗时,所以我们这里前面把锁释放了,这里要通知生产者,需要再拿锁
synchronized (monitor) {
monitor.notify();
}
}
}
};
Thread thread1 = new Thread(consumerRunnable);
thread1.setName("consumer");
thread1.start();
}
}
日志如下:
2020-06-27 13:02:37[INFO] Demo$1.run(Demo.java:35) producer start produce
2020-06-27 13:02:39[INFO] Demo$1.run(Demo.java:44) producer produce 115
------------- 这里看时间,可以看出,生产完了,消费者马上消费
2020-06-27 13:02:39[INFO] Demo$2.run(Demo.java:89) consumer start consume 115
2020-06-27 13:02:40[INFO] Demo$2.run(Demo.java:94) consumer consume 115,spent 1
-------------- 10 s后
2020-06-27 13:02:49[INFO] Demo$1.run(Demo.java:35) producer start produce
2020-06-27 13:02:51[INFO] Demo$1.run(Demo.java:44) producer produce 558
2020-06-27 13:02:51[INFO] Demo$2.run(Demo.java:89) consumer start consume 558
2020-06-27 13:02:52[INFO] Demo$2.run(Demo.java:94) consumer consume 558,spent 1
上面这个应该是正确的版本,即:生产完了,消费者可以立马消费。
网上的部分代码实现,比如:
这个代码问题在于,生产完了,但是消费者也消费不了,因为锁没释放。这个是有问题的
https://www.geeksforgeeks.org/producer-consumer-solution-using-threads-java/