初学java多线程,IllegalMonitorStateException错误记录
i++导致i的对象发生了改变,导致第二次循环的时候,synchronized的对象与i.notify()的对象不一致,i.notify()未获取对应的锁。

private final Integer i = 10;添加final后,i++;报错

解决办法:synchronized (this),以当前类为资源被锁定!

最后贴一下正常运行的代码,实现了最基本的线程通信
package com.Fran.Thread;
public class TestSnycInteger implements Runnable{
private int i = 0;
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
TestSnycInteger testSnycInteger = new TestSnycInteger();
Thread t1 = new Thread(testSnycInteger,"james");
Thread t2 = new Thread(testSnycInteger,"kobe");
t1.start();
Thread.sleep(100);
t2.start();
}
@Override
public void run() {
String name = Thread.currentThread().getName();
// TODO Auto-generated method stub
if(name.equals("james")) {
synchronized (this) {
for(;;) {
if(i == 5) {
System.out.println("开始释放锁");
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(name+" start to thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.notify();//i.notify()未获取对应的锁。出现了java.lang.IllegalMonitorStateException错误
i++; //i的对象发生了改变,导致第二次循环的时候,i.notify()未获取对应的锁。
System.out.println(name+" notyfiy : "+i);
}
}
}
else {
synchronized (this) {
System.out.println(name+" start to thread 2");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name+" end to thread 2");
this.notify();
}
}
}
}
注意: 线程notify或者wait时,要确保拿到了对应的锁!
本文深入探讨了Java多线程中IllegalMonitorStateException的产生原因,通过实例解析了i++操作如何引发对象状态变化,导致锁不一致的问题,并提供了解决方案。文章强调了在使用synchronized和notify时正确获取锁的重要性。
627

被折叠的 条评论
为什么被折叠?



