日期:2014-05-20  浏览次数:20772 次

异常捕获问题
class StopThread implements Runnable
{
private boolean flag =true;
public  void run()
{
while(flag)
{

try{
wait();
}
catch(InterruptedException e)
{
System.out.println(Thread.currentThread().getName()+"....Exception");
flag=false;
}
System.out.println(Thread.currentThread().getName()+"....run");
}
}
public void changeFlag()
{
flag = false;
}
}




class  StopThreadDemo
{
public static void main(String[] args) 
{
StopThread st = new StopThread();

Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();

int num = 0;

while(true)
{
if(num++ == 60)
{
//st.changeFlag();
t1.interrupt();
//t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()+"......."+num);
}
System.out.println("over");
}
}
运行时提示错误 ,
main....58
main....59
main....60
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at my.operate.demo.StopThreadDemo.run(StopThread.java:33)
at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at my.operate.demo.StopThreadDemo.run(StopThread.java:33)
at java.lang.Thread.run(Unknown Source)
就是wait捕获异常不对?自己也没有写错啊,求高手啊
异常 exception java thread

------解决方案--------------------
        synchronized (this) {
         wait();
        }