读书人

线程notify()解决方法

发布时间: 2012-01-29 21:39:32 作者: rapoo

线程notify()
package student;
class teacher{
public synchronized void say(){


System.out.println("在说话");
//Thread.sleep(100000);

try {
this.wait();
} catch (InterruptedException e) {

e.printStackTrace();
}
System.out.println("我醒了@");
}

public synchronized void sayhello(){
System.out.println("我在说hello");


}
}
class thread1 implements Runnable{
public static teacher tea=new teacher();
public void run(){


try {
tea.say();



} catch (Exception e) {

e.printStackTrace();
}

}



}

public class Demo{

public static void main(String[] args){


thread1 tre=new thread1();
new Thread(tre).start();
try {
Thread.sleep(1222);
} catch (InterruptedException e) {

e.printStackTrace();
}
thread1.tea.sayhello();
thread1.tea.notify();//这里提示错误了!


}

}
提示是:java.lang.IllegalMonitorStateException异常!、
请大虾看看!


[解决办法]
同步块中才能使用wait和notify
否则就是报这个错

读书人网 >J2SE开发

热点推荐