Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chapter007 opened this issue Mar 27, 2019 · 0 comments

Comments

@chapter007
Copy link

chapter007 commented Mar 27, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant