其他分享
首页 > 其他分享> > 使用wait notify 报错 IllegalMonitorStateException

使用wait notify 报错 IllegalMonitorStateException

作者:互联网

 

解决办法:相关的wait及notify需要在synchronized修饰的方法下执行

Object object = new Object();
new Thread(() -> {
    for (int i = 0; i < 10; i++) {
        try {
            synchronized (object) {
                object.wait();
            }
            System.out.println("wait end:" + i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}).start();
new Thread(() -> {
    for (int i = 0; i < 10; i++) {
        System.out.println("notify start:" + i);
        synchronized (object) {
            object.notify();
        }
    }
}).start();

 

标签:synchronized,IllegalMonitorStateException,object,start,报错,notify,new,wait
来源: https://www.cnblogs.com/u1w2/p/16493671.html