我有一段这样的代码
Dotry try1=new Dotry("线程1");
Dotry try2=new Dotry("线程2");
try1.start();
try1.join();
Thread.sleep(2000);
try1.wait();
try2.start();
调试后报错我想问一下时怎么回事啊?
class Dotry extends Thread{
String name;
public Dotry(String name){
this.name=name;
}
public void run(){
for(int i=15;i>0;i--){
System.out.println(name+"在运行");
}
}
}
http://macleo.iteye.com/blog/625873
如果当前线程不是此对象监视器的所有者,就会抛出该异常,也就是说调用wait方法之前,必须先获取该对象的同步监视器。正确的使用语法必须是:
synchronized(try1){
try1.wait();
}
其实你可以F3看下这个wait方法的源码,API文档的注释是这样的:
* <pre>
* synchronized (obj) {
* while (<condition does not hold>)
* obj.wait();
* ... // Perform action appropriate to condition
* }
* </pre>
* This method should only be called by a thread that is the owner
* of this object's monitor. See the {@code notify} method for a
* description of the ways in which a thread can become the owner of
* a monitor.