Skip to content

生产者/消费者那篇文章,最后的多生产/多消费代码实现有点问题吧 #57

Description

@chapter007

原文是使用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。
结果正常

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions