简体   繁体   English

java.lang.IllegalMonitorStateException 从线程中运行的方法抛出

[英]java.lang.IllegalMonitorStateException being thrown from methods running in threads

I am trying to create basic producer/consuner class using:我正在尝试使用以下方法创建基本的生产者/消费者 class:

public class ProducerConsumer {
    private final static int MAX_SIZE = 100;
    private Queue<String> data = new PriorityQueue<>();
    private Lock lock = new ReentrantLock();
    private Condition bufferFull = lock.newCondition();
    private Condition bufferEmpty = lock.newCondition();

    public void produce(){
        while(true) {
            try {
                lock.lock();
                while (data.size() >= MAX_SIZE) {
                    bufferFull.await();
                }
                addData();
                bufferEmpty.notifyAll();
            } catch (InterruptedException e) {
                System.out.println("error produce");
            } finally {
                lock.unlock();
            }
        }
    }
    public void consume(){
        while(true) {
            try {
                lock.lock();
                while (data.isEmpty()) {
                    bufferEmpty.await();
                }
                String value = data.poll();
                System.out.println("Thread " + Thread.currentThread().getName() + " processing value " + value);
                bufferFull.notifyAll();
            } catch (InterruptedException e) {
                System.out.println("error consume");
            } finally {
                lock.unlock();
            }
        }
    }

    private void addData(){
        IntStream.range(0,10).forEach( i ->
                data.add(new Date().toString())
        );
    }

    public void start(int consumerNumber){
        IntStream.range(0,consumerNumber)
                .mapToObj(i -> new Thread(this::consume))
                .collect(Collectors.toList())
                .forEach(Thread::start);

        Thread t = new Thread(this::produce);
        t.start();
    }

} 

However it keeps throwing error: java.lang.IllegalMonitorStateException.但是它不断抛出错误:java.lang.IllegalMonitorStateException。 My question is, why does it throw this error?我的问题是,为什么它会抛出这个错误? method of this intance are running in threads, so they should own condition lock thus i dont understand meaning behind this error.此实例的方法在线程中运行,因此它们应该拥有条件锁,因此我不明白此错误背后的含义。

Thanks for help!感谢帮助!

bufferEmpty.notifyAll() is the wrong method to call. bufferEmpty.notifyAll()是错误的调用方法。 That method requires you hold the monitor on the "bufferEmpty" object itself, which is unrelated to the lock instance you're using.该方法要求您将监视器放在“bufferEmpty”object 本身上,这与您正在使用的lock实例无关。

The right method to call is正确的调用方法是

bufferEmpty.signalAll();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM