[英]wait() and notify() method , always IllegalMonitorStateException is happen and tell me current Thread is not Owner Why?
package pkg_1;
public class ExpOnWaitMethod extends Thread {
static Double x = new Double(20);
public static void main(String[] args) {
ExpOnWaitMethod T1 = new ExpOnWaitMethod();
ExpOnWaitMethod T2 = new ExpOnWaitMethod();
T1.start();
T2.start();
}
public void run() {
Mag mag = new Mag();
synchronized (x) {
try {
for (int i = 1; i < 10; i++) {
mag.nop(Thread.currentThread());
x = i * 2.0;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Mag {
char ccc = 'A';
public void nop(Thread thr) throws InterruptedException {
System.out.print(ccc + " ");
ccc++;
if (thr.getState().toString().equalsIgnoreCase("runnable"))
Thread.currentThread().wait();
//thr.notify();
}
}
You need to hold the lock on the object you want to wait
on (you can only call it within a synchronized
block).您需要锁定您想要wait
的对象(您只能在synchronized
块中调用它)。
Also, calling wait
on a Thread
is very unusual and probably not what you want.此外,在Thread
上调用wait
是非常不寻常的,可能不是您想要的。
I am not sure what you are trying to do, but could you be confusing wait
with sleep
?我不确定您要做什么,但是您会混淆wait
和sleep
吗?
If you want to wait for another thread to finish, that would be anotherThread.join()
.如果你想等待另一个线程完成,那就是anotherThread.join()
。
Before you call wait
on an object, you must acquire that object's lock:在对对象调用wait
之前,您必须获取该对象的锁:
synchronized(obj)
{
obj.wait();
}
Your code is calling wait
on a Thread
object without acquiring the lock first.您的代码在没有先获取锁的情况下调用Thread
对象的wait
。
I assume this is just a simplified test case to show your problem, but note that you probably want to be calling wait
on an object that is accessible from all threads, not on the Thread
objects themselves.我认为这只是一个简化的测试用例来显示您的问题,但请注意,您可能希望在一个可从所有线程访问的对象上调用wait
,而不是在Thread
对象本身上调用。
Someone should cite the API contract for java.lang.Object.wait()
, which explains this directly.有人应该引用java.lang.Object.wait()
的 API 契约,它直接解释了这一点。 If a method raises an exception, read the documentation.如果方法引发异常,请阅读文档。
When in doubt, read the contract.如有疑问,请阅读合同。 (Bill McNeal on NewsRadio always kept his in his jacket pocket, a good metaphor for the JavaDoc API.. see "Crazy Prepared" under NewsRadio and ponder the imponderable.) (NewsRadio 上的 Bill McNeal 总是把他的口袋放在夹克口袋里,这是 JavaDoc API 的一个很好的比喻。请参阅NewsRadio下的“Crazy Prepared”并思考不可估量的事情。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.