016Java问题记录001IllegalMonitorStateException

本文详细分析了Java中IllegalMonitorStateException异常产生的两个原因:锁对象发生改变和锁定错误的对象,并通过代码实例解析了问题所在及相应的解决方案,强调了在使用锁时需要注意的对象一致性与锁的选择。
摘要由CSDN通过智能技术生成

部分内容来自以下博客:

https://blog.csdn.net/historyasamirror/article/details/6709693

1 锁对象发生了改变

在测试多线程通信的代码时,出现了这个异常。

1.1 代码分析

代码如下:

public class Demo {
    public static void main(String[] args) {
        DemoThread demoThread = new DemoThread();
        Thread thread1 = new Thread(demoThread);
        Thread thread2 = new Thread(demoThread);
        thread1.start();
        thread2.start();
    }
}

class DemoThread implements Runnable {
    private Integer num = 1;

    @Override
    public void run() {
        while (true) {
            synchronized (num) {
                num.notify();
                if (num <= 10) {
                    System.out.println(Thread.currentThread().getName() + " >>> " + num++);
                    try {
                        num.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

运行结果如下:

Thread-0 >>> 1
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
    at java.lang.Object.notify(Native Method)
    at com.iyao.ide.engine.task.DemoThread.run(Demo.java:22)
    at java.lang.Thread.run(Thread.java:745)
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值