class MyThread extends Thread{
String sa;
public MyThread(String sa){
this.sa=sa;
}
public void run(){
synchronized(sa){
while(!sa.equals("done")){
try{
sa.wait();
}catch(InterruptedException e){
System.out.println("haha");
}
}
}
System.out.println(sa);
}
}public class ThreadTest {
private static String sa=new String("not done");
public static void main(String[] args){
MyThread mt=new MyThread(sa);
mt.start();
synchronized(sa){
try{
sa=new String("done");
sa.notify();
}catch(Exception e1){
e1.printStackTrace();//错误在这里抛出
}
}
}
}
问题是:错误虽然抛出,但并不是我想要的InterruptedException,请问为什么会抛出异常?

解决方案 »

  1.   

    个人理解:在main函数中sa=new String("done");已近使得MyThread类和main函数中的不是对一个String对象进行“加锁,释放锁 ”操作了,所以程序如果没有异常的话,会使一直等待状态,至于抛出“java.lang.IllegalMonitorStateException: current thread not owner”,因该是由于“sa=new String("done");”,改变了锁对象,这点不是清楚,同望牛人指教
      

  2.   

    MyThread mt=new MyThread(sa);把sa传给MyThread ,while(!sa.equals("done")){
    try{
    sa.wait();
    }使占用sa的对象锁,
    在main函数中
    synchronized(sa){
    try{
    sa=new String("done");
    sa.notify();
    }肯定会跑出异常,sa=new String("done");重新申请了一个对象你调用sa.notify();此时sa并没有被wait,主要是sa属于不同对象!下面是我改的代码:可以正常执行!
    package mypackae;
    class MyThread extends Thread{
    String sa;
    public MyThread(String sa){
    this.sa=sa;
    }
    public void run(){
    synchronized(sa){
    while(!sa.equals("done")){
    try{
    sa.wait();
    }catch(InterruptedException e){
    System.out.println("haha");
    }
    }
    }
    System.out.println(sa);
    }
    public void set(String str)
    {
    this.sa=str;
    }
    }
    public class Main 
    { public static void main(String[] args){
    String sa=new String("not done");
    MyThread mt=new MyThread(sa);
    mt.start();
    synchronized(sa){
    try{
    sa.notify();
    mt.set("done");

    }catch(Exception e1){
    System.out.println(sa);
    e1.printStackTrace();
    }
    }
    }
    }
      

  3.   

    package mypackae;class MyThread extends Thread
    {
    String sa; public MyThread(String sa)
    {
    this.sa = sa;
    } public void run()
    {
    synchronized (sa)
    {
    while (!sa.equals("done"))
    {
    try
    {
    sa.wait();
    } catch (InterruptedException e)
    {
    System.out.println("haha");
    }
    }
    }
    System.out.println(sa);
    } public void set(String str)
    {
    this.sa = str;
    }
    }public class Main
    { public static void main(String[] args)
    {
    String sa = new String("not done");
    MyThread mt = new MyThread(sa);
    mt.start();
    for (int i = 1; i < 10; i--)
    { }
    synchronized (mt)
    {
    try
    {
    mt.interrupt();
    mt.set("done"); } catch (Exception e1)
    {
    System.out.println(sa);
    e1.printStackTrace();
    }
    } }}
    这个代码会产生InterruptedException 异常!因为对一个进入中断状态的线程调用中断会产生该异常!