初学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时,要确保拿到了对应的锁!