使用多线程运行Odd甚至程序时获取异常

时间:2016-10-05 06:05:53

标签: java multithreading

我正在尝试运行以下书面程序。但在这里我得到了例外

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)

我无法找到异常背后的原因。

在notify方法中发生执行。只有当前线程不拥有锁对象时,才会在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();
}

}

1 个答案:

答案 0 :(得分:3)

要在对象上调用notify(),您需要锁定该对象,即在该对象上同步的块中。您处于同步区块中,但在ob上进行同步时,您正在notify()上呼叫this

您必须在obnotify()来电时使用wait(),或在this上同步。