代码之家  ›  专栏  ›  技术社区  ›  Sameer

此生产者消费者的非法监视状态异常?[副本]

  •  1
  • Sameer  · 技术社区  · 8 年前

    这个问题已经有了答案:

    试图用Java中的一个简单计数器来练习生产者和消费者。 不知道为什么我在这段代码上得到一个非法的监视器状态异常。

    我有在自己的线程中运行的counter rest和counter consume方法。 计数器本身是一个静态int volatile字段。 counter类还为您提供一个

    如果我将wait naotify更改为以下值:

    Counter.lock.notify();
    Counter.lock.wait();
    

    代码有效。Dosen't wait()和notify()会自动获取锁同步是否打开的引用?

    生产者类

    package multithreading;
    
    
    public class CounterProducer implements Runnable {
    
    
    public void run() {
    
        try {   incrCounter();   } catch (InterruptedException e) {            e.printStackTrace();        }
    }
    
    public void incrCounter() throws InterruptedException {
    
    
        while (true) {
            synchronized (Counter.lock) {
                if (Counter.counter < 1) {
                    System.out.println("Counter Reset");
                    Counter.counter = 10;
                    notify();
                    wait();
                }
    
    
            }
        }
    
    
    }
    

    }

    消费阶层

    package multithreading;
    
    
    public class CounterConsumer implements Runnable {
    
    
        public void run() {
    
            try {   consumeCounter();   } catch (InterruptedException e) {            e.printStackTrace();        }
        }
    
        public void consumeCounter() throws InterruptedException {
    
    
            while (true) {
                synchronized (Counter.lock) {
                    if (Counter.counter > 0) {
                        System.out.println("Consumed");
                        Counter.counter--;
                        notify();
                        wait();
                    }
    
    
                }
            }
    
    
        }
    
    }
    
    The Counter
    
    public class Counter {
    
        public static volatile int counter;
    
        public static final Object lock = new Object();
    
    }
    

    柜台

    public class CounterRunner {
    
        public static void main(String[] args) {
    
            Thread con = new Thread(new CounterConsumer());
            Thread prod = new Thread(new CounterProducer());
    
            con.start();
            prod.start();
    
        }
    
    
    }
    

    跑步者

    公共类计数器{
    
    公共静态void main(string[]args){
    
    thread con=新线程(new counter consumer());
    thread prod=新线程(new counterproducer());
    
    con.start();
    生产开始();
    
    }
    
    
    }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Solomon Slow    8 年前

    如果我将wait naotify更改为以下值,则代码有效:

    Counter.lock.notify();
    Counter.lock.wait();
    

    每个java方法要么是某个类的静态方法,要么是某个对象的实例方法。如果看到不包含显式类名或对象引用的方法调用,则它是对属于 this 目标

    也就是说, notify() 意思是一样的 this.notify() ,和 wait() 方法 this.wait() .

    这 ,表示 CounterProducer 当它出现在 CounterProducer.incrCounter() 方法,它引用 CounterConsumer 当它出现在 CounterConsumer.consumeCounter() 方法。