生产者/消费者那篇文章,最后的多生产/多消费代码实现有点问题吧
Opened this issue · 0 comments
chapter007 commented
原文是使用reentrantLock和condition来实现多生产,多消费模式,但是再开启多个线程的时候传入的是同一个condition,并不能控制多个线程
public static void main(String[] args) throws InterruptedException {
ReentrantLock lock = new ReentrantLock();
Condition newCondition = lock.newCondition();
Product product = new Product(lock,newCondition);
Consumer consumer = new Consumer(lock,newCondition);
for(int i=0;i<3;i++){
ThreadProduct pThread = new ThreadProduct(product);
ThreadConsumer cThread = new ThreadConsumer(consumer);
pThread.start();
cThread.start();
}
}
这样运行的结果也有问题,会有两个线程get不到val
修改为
public static void main(String[] args){
ReentrantLock lock = new ReentrantLock();
for (int i=0;i<3;i++){
Condition condition = lock.newCondition();
Producer producer = new Producer(lock,condition);
Consumer consumer = new Consumer(lock,condition);
ProducerThread producerThread = new ProducerThread(producer);
ConsumerThread consumerThread = new ConsumerThread(consumer);
producerThread.start();
consumerThread.start();
}
}
就是每个线程里有一个condition,一个reentrantlock可以有多个condition。
结果正常