Doing something...
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at MyTest.test(MyTest.java:13)
at MyTest.main(MyTest.java:3)
应该就是赋值的问题! 查看Object类的源代码,关于notifyAll的说明指向去参考notify的说明,里面说道: This method should only be called by a thread that is the owner of this object's monitor 是对象的monitor有三种方式: * <li>By executing a synchronized instance method of that object. * <li>By executing the body of a <code>synchronized </code> statement * that synchronizes on the object. * <li>For objects of type <code>Class, </code> by executing a * synchronized static method of that class. 这个赋值与Java的对象类型有关,当对一个Boolean赋值为一个boolean型值时,导致原来的lock 所指的对象成为了一个新的boolean的包装类,这样前面的synchronized(lock)就失效了,所以报 除了异常,尝试下面的例子,我们对一个Object调用了一系列的方法来做,lock指向的对象并没有发生 变化,所以synchronized仍然有效,就不会报错了,
不过,只是觉得好像是这样,呵呵。
请尝试一下的代码,运行无误
Java code
publicclass MyTest {
publicstaticvoid main(String[] args) throws Exception {
new TestThread().start();
new TestThread().start();
Thread.sleep(1000);
System.out.println("Doing something...");
synchronized (lock) {
lock.setIII(2);
lock.notifyAll();
}
System.exit(0);
}
staticvolatile AAA lock =new AAA(1);
}
class TestThread extends Thread {
@Override
publicvoid run() {
synchronized (MyTest.lock) {
while (MyTest.lock.getIII()==1) {
try {
MyTest.lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(getId());
}
}
}
class AAA {
int iii;
public AAA(int i){
iii = i;
}
publicvoid setIII(int i){
iii = i;
}
publicint getIII(){
return iii;
}
}
Exception in thread "pool-1-thread-20" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method) at thread1.ParaNull.LogicalProcess.run(LogicalProcess.java:367) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907) at java.lang.Thread.run(Thread.java:619) 错误