简体   繁体   English

使用多线程运行奇数偶程序时获取异常

[英]Getting Exception while running Odd even program using multiple thread

I am trying to run below written program. 我正在尝试在书面程序下运行。 But Here I am getting exception as 但是在这里我得到了例外

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at main.java.OddEven$even.run(OddEven.java:16)
at java.lang.Thread.run(Unknown Source)

I am unable to find reason behind exception. 我找不到异常背后的原因。

Execption is occuring in notify method. 通知方法中正在执行。 We get IllegalMonitorStateException in notify method only when current thread does not own the lock object. 仅当当前线程不拥有锁对象时,才在notify方法中获得IllegalMonitorStateException。

public class OddEven {

private Integer count = 0;
Object ob = new Object();

class even implements Runnable {

    @Override
    public void run() {
            while (count % 2 == 0) {
                synchronized (ob) {
                if (count % 2 == 0) {
                    System.out.println(count++);
                    notify();
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
        }

    }
}

class odd implements Runnable {
    @Override
    public void run() {
            while (count % 2 != 0) {
                synchronized (ob) {
                if (count % 2 != 0) {
                    System.out.println(count++);
                    notify();
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
        }

    }

}

public static void main(String[] args) throws CloneNotSupportedException {
    OddEven t1 = new OddEven();
    Thread e = new Thread(t1.new even());
    Thread o = new Thread(t1.new odd());
    e.start();
    o.start();
}

} }

To call notify() on an object you need to have a lock on that object, ie be in a block synchronized on that object. 要在对象上调用notify() ,您需要对该对象进行锁定,即在该对象上同步的块中。 You are in a synchronized block, but you are synchronizing on ob , while you are calling notify() on this . 您处于同步块中,但是在this上调用notify()时,正在ob上进行同步。

You either have to also use ob for your notify() and wait() calls, or synchronize on this . 您还必须在您的notify()wait()调用中使用ob ,或者在this同步。

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

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